溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue如何替代marquee標(biāo)簽超出寬度文字橫向滾動(dòng)效果

發(fā)布時(shí)間:2021-06-26 13:37:06 來(lái)源:億速云 閱讀:466 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了Vue如何替代marquee標(biāo)簽超出寬度文字橫向滾動(dòng)效果,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

一、npm 安裝

如果你想安裝插件(自己寫的)

安裝

# install dependencies
npm i marquee-components

使用

在main.js引入

import marquee from 'marquee-components'
Vue.use(marquee );

在頁(yè)面使用

<template>
 <div id="app">
    <marquee :val="msg"></marquee>
 </div>
</template>
<script>
export default {
 name: 'app',
 data () {
  return {
   msg: 'vuevuevuevuevuevuevuevuevuevuevuevuevuevuevuevuevue'
  }
 }
}
</script>

val后加文字即可,當(dāng)超過(guò)文本容器長(zhǎng)度時(shí),觸動(dòng)橫向滾動(dòng)效果。

二、直接引入組件

marquee組件

<template>
 <div class="marquee-wrap">
  <div class="scroll">
   <p class="marquee">{{text}}</p>
   <p class="copy"></p>
  </div>
  <p class="getWidth">{{text}}</p>
 </div>
</template>

<script>
export default {
 name: 'marquee',
 props: ['val'],
 data () {
  return {
   timer: null,
   text: ''
  }
 },
 created () {
  let timer = setTimeout(() => {
   this.move()
   clearTimeout(timer)
  }, 1000)
 },
 mounted () {
  for (let item of this.val) {
   this.text += ' ' + item
  }
 },
 methods: {
  move () {
   let maxWidth = document.querySelector('.marquee-wrap').clientWidth
   let width = document.querySelector('.getWidth').scrollWidth
   if (width <= maxWidth) return
   let scroll = document.querySelector('.scroll')
   let copy = document.querySelector('.copy')
   copy.innerText = this.text
   let distance = 0 
   this.timer = setInterval(() => {
    distance -= 1
    if (-distance >= width) {
     distance = 16
    }
    scroll.style.transform = 'translateX(' + distance + 'px)'
   }, 20)
  }
 },
 beforeDestroy () {
  clearInterval(this.timer)
 }
}
</script>

<style scoped>
 .marquee-wrap {
  width: 100%;
  overflow: hidden;
  position: relative;
 }
 .marquee{
  margin-right: 16px;
 }
 p {
  word-break:keep-all;
  white-space: nowrap;
  font-size: 16px;
  font-family: "微軟雅黑 Light";
 }
 .scroll {
  display: flex;
 }
 .getWidth {
  word-break:keep-all;
  white-space:nowrap;
  position: absolute;
  opacity: 0;
  top: 0;
 }
</style>

其他頁(yè)面引入marquee組件

<template>
 <div class="container">
    <marquee :val="title"></marquee>
 </div>
</template>
<script>
import marquee from './marquee'
 name: 'index',
 components: {
  marquee
 },
 data () {
  return {
 title: ''
  }
 },
</script>

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Vue如何替代marquee標(biāo)簽超出寬度文字橫向滾動(dòng)效果”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI