vue 纯js实现广告文字滚动——横向

1.先上效果

 

本想弄个动态图的 但是我不会 /(ㄒoㄒ)/~~

那我只能用些图片替代,向左滚动效果,无限循环

 

 

2.原理

 利用滚动文本的div margin-left实现

一两句话说不清楚 直接上个草稿(虽然不知道看得吃不吃力)

 

 

以上可以看到有2个宽,一个是窗口的,一个是文本文字的

根据这2个已知量去动态控制左边距的量

 

3.实现

html

<div class="companySDL_scrollText">
    <div class="companySDL_scrollText__item"
         ref="srcollText">
      今日生猪行情报价:1000元/头 1今日生猪行情报价:今日生猪行情报价:1000元/头 2今日生猪:<span style="color:red">上涨:10%</span>
    </div>
  </div>

css

.companySDL_scrollText {
  position: relative;
  height: 100%;
  margin-left: 40%;
  width: 500px;
  overflow: auto;
  &__item {
    display: inline-block;
    font-size: 16px;
    color: #d8edff;
    height: 76px;
    white-space: nowrap;
    text-align: center;
  }
  ::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
  }
}

js

 1  data () {
 2     return {
 3       addWidth: 0, //左边距
 4       timer: 0,
 5       divWidth: 500, // 跟css配置宽一致
 6       textWidth: 0
 7     }
 8   },
 9   methods: {
10     scrollToLeft (value) {
11       this.addWidth = Number(this.addWidth) + Number(value)
12       this.$refs.srcollText && (this.$refs.srcollText.style.marginLeft = this.addWidth + 'px') // 设置左边距
13       if (-this.addWidth > this.textWidth) { // 滚动完成
15 this.addWidth = this.divWidth // 重置左边距
17 } 18 } 19 }, 20 mounted () { 21   this.$nextTick(() => { 22 this.timer = setInterval(() => { this.scrollToLeft(-10) }, 250) 23 this.textWidth = document.defaultView.getComputedStyle(this.$refs.srcollText, '').width.split('px')[0] 24 console.log('文本宽度', this.textWidth) 25 }) 26 },

 

代码解析

获取文本宽度

document.defaultView.getComputedStyle(this.$refs.srcollText, '').width.split('px')[0]

启动向左滚动的定时器,每次挪动10px,我直接设置为负数

setInterval(() => { this.scrollToLeft(-10) }, 250)

 

完~

 

posted @ 2022-01-20 11:41  树叶铃铛  阅读(1346)  评论(0编辑  收藏  举报