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)

 

完~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM