vue 通知 走马灯效果

封装一个子组件:

<template>
  <div class="container">
      <div class="wrap"> 
    <div id="box">
      <div id="marquee">{{text}}</div> 
      <div id="copy"></div> 
    </div>
    <div id="node">{{text}}</div>
  </div>
  </div>
</template>
<script>
export default {
  name: 'Marquee',
  props: ['text'],  // 字符串格式
  data () {
    return {
    }
  },
  methods: {
    move () {
// 获取文字text 的计算后宽度  (由于overflow的存在,直接获取不到,需要独立的node计算)
      let width = document.getElementById('node').getBoundingClientRect().width 
      let box = document.getElementById('box')
      let copy = document.getElementById('copy')
      copy.innerText = this.text // 文字副本填充
      let distance = 0 // 位移距离
//设置位移
      setInterval(function () { 
        distance = distance - 1
 // 如果位移超过文字宽度,则回到起点
        if (-distance >= width) {
          distance = 16
        }
        box.style.transform = 'translateX(' + distance + 'px)'
      }, 40) 
    }
  },
// 把父组件传入的arr转化成字符串
  mounted () {
  },
// 更新的时候运动
  updated: function () {
    this.move()
  }
}
</script>
<style lang="less" scoped>
  @import '../assets/less/common.less';
// 限制外框宽度,隐藏多余的部分
.container{
    font-size: 26/@size;
    background: url(../assets/img/purchasedMembers/ic_laba.png) white no-repeat 20/@size 50%;   //通知的一个icon图标
    background-size: 32/@size 28/@size;
    padding-left:64/@size;
    margin-top: 0.266rem;
    /*border-bottom: 1px solid #F1F1F1;*/
    height: 1rem;
}
.wrap {
   overflow: hidden;
    height: 1rem;
}
// 移动框宽度设置
#box {
  width: 8000%;
}
// 文字一行显示
#box div {
  float: left;
}
// 设置前后间隔
#marquee {
   margin-right:16/@size;
   line-height: 1rem;
}
// 获取宽度的节点,隐藏掉
#node {
  position: absolute;
  z-index: -999;
  top: -999999px;
}
</style>

父组件引用并传参:

      

<news :text="text"></news>

猜你喜欢

转载自www.cnblogs.com/skin-blue/p/10337475.html