vue

使用vue + css3实现一个跑马灯

2019-10-17  本文已影响0人  羽晞yose

工作中需要用到一个跑马灯,网上找了一下,各种妖魔做法都有,明明很简单的东西,却要使用拼接字符串、使用计时器、还有各种文案复制什么的,更有甚者各种id,还没从jq中走出来的样子,思路上让我看了略感忧伤,而且测试了一番还有bug,所以还是自己动手写一个,其实用css3来写思路清晰,代码量少

跑马灯效果图
<template>
  <section class="marquee-wrap">
      <div class="marquee" ref="marquee" :style="{'animationDuration': duration}">
            <span class="text-item" v-for="(item, index) of data" :key="index">{{item}}</span>
            <span class="text-item" v-for="(item, index) of data" :key="`copy-${index}`">{{item}}</span>
      </div>
  </section>
</template>

<script>
export default {
    name: 'marquee',
    props: {
        /* 跑马灯数据 */
        data: {
            type: Array,
            default: () => []
        },
        /* 跑马灯速度,数值越大速度越快 */
        speed: {
            type: Number,
            default: 50
        }
    },
    data () {
        return {
            duration: 0
        };
    },
    mounted () {
        /* 跑马灯速度,使用跑马灯内容宽度 除以 速度 得到完整跑完一半内容的时间 */
        this.duration = ~~this.$refs.marquee.getBoundingClientRect().width / this.speed +'s';
    }
};
</script>

<style lang="less" scoped>
// 自行使用 px2rem,这部分不讲述

.marquee-wrap {
    position: relative;
    overflow: hidden;
    &:after {
        content: '0';
        opacity: 0;
    }
}

.marquee {
    position: absolute;
    font-size: 0;
    white-space: nowrap;
    animation-name: marquee;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

.text-item {
    margin-right: 24px;
    font-size: 24px;
    /* 解决Font Boosting */
    -webkit-text-size-adjust: none;
    // max-height: 999px; //如果上面的依然未解决问题就加上这句吧
}

@keyframes marquee {
    to { transform: translateX(-50%);}
}
</style>

这里只对跑马灯效果进行封装,文字颜色,外边框,喇叭等等都由外部定义,比如以上效果图,这样做的好处是方便重新定义跑马灯样式,本人不喜欢对组件进行各种默认定义,否则更改起来各种deep特别忧伤

<div class="marquee">
    <marquee :data="options.marquee"></marquee>
</div>

<style lang="less" scoped>
// 自行使用 px2rem,这部分不讲述

.marquee {
    width: 544px;
    padding-left: 100p;
    padding-right: 30px;
    line-height: 50px;
    margin: 0 auto 28px;
    color: #fff;
    box-sizing: border-box;
    border: 1px solid #f2b0ab;
    border-radius: 26px;
    background: url(../img/sound.png) no-repeat 42px center / 35px 35px;
}
</style>

这里说一下为什么要对marquee-wrap使用为了添加个0,因为absolute后失去了高度,用伪类补一个看不见的文字0来重新撑开可视高度。对于marquee使用absolute有两个原因:一是对于css3动画,我的习惯都会新建图层;二是我需要获取到所有文案撑开出来的宽度,使用absolute后可以让该节点宽度自行撑出来,直接获取即可。

上一篇下一篇

猜你喜欢

热点阅读