vue2实现文字跑马灯效果

第一种方式

html

 <!-- 滚动通知 -->
  <div class="info">
    <div class="text">&nbsp;</div>
  </div>

CSS

.info{
  display: flex;
  overflow: hidden;
  text-overflow: ellipsis;
  height:30px;
  line-height: 30px;
  padding-left: .5rem;
  margin-bottom: 5px;
  border: 1px solid transparent;
  background-clip: padding-box, border-box;
  background-origin: padding-box, border-box;
  background-image: linear-gradient(to right, #082e5d, #001531),linear-gradient(90deg, #3579CB, #011532);
  font-size: calc(100vw * 12 / 1920);
  width:100%;
  color: #fff;
  ::v-deep span{
    color: #7CB8FE;
    font-weight: 600;
    //padding:0 5px;
  }
}

JS

move(zoumadeng){
      const info = document.querySelector(".info"); // 容器元素
      const textNode = document.querySelector(".info > .text"); // 文字元素
      textNode.innerHTML= textNode.innerHTML + zoumadeng
      // container.appendChild(textNode.cloneNode(true)); // 复制元素到后方
      const textWidth = textNode.offsetWidth; // 获取文字元素宽度
      let count = info.offsetWidth; // 初始化向左偏移为容器大小
      const loop = () => {
          if(count <= -textWidth) { // 如果文字偏移超出一个文字元素的宽度则复原
            textNode.style["margin-left"] = 0;
            count = info.offsetWidth
          }
          textNode.style["margin-left"] = `${count--}px`; // 继续向左移动
          window.requestAnimationFrame(() => loop()); // 动画递归调用
      }
      window.requestAnimationFrame(() => loop()); // 启动动画
    },

第二种方式

html

<div class="info">
 		<div v-html="text"></div>
 </div>

CSS

.info{
  height:30px;
  line-height: 30px;
  padding-left: .5rem;
  margin-bottom: 5px;
  border: 1px solid transparent;
  background-clip: padding-box, border-box;
  background-origin: padding-box, border-box;
  background-image: linear-gradient(to right, #082e5d, #001531),linear-gradient(90deg, #3579CB, #011532);
  font-size: calc(100vw * 12 / 1920);
  overflow: hidden;
  width:100%;
  color: #fff;
  ::v-deep span{
    color: #7CB8FE;
    font-weight: 600;
    //padding:0 5px;
  }
}

这里有一点要注意的是:v-html 的样式,直接写在外部样式可能不会生效。可以尝试使用穿透样式(::v-deep 或者 >>>)

JS

lang() {
        //阻止lang再次执行
        if (this.setInterval != null) return
        // 使用substring截取字符串
        this.setInterval = setInterval(() => {
            //获取头一个 字符
            let qian = this.text.substring(0, 7)
            //获取后面的所有字符
            let hou = this.text.substring(7)
            //将获取到的字符拼接起来
            this.text = hou + qian

            // this.text = this.text
        }, 800)
    },

这种是通过截取字符串的方式实现滚动,如果文本中含有 html 标签的时候可能会出现标签展现在页面中的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码搬运媛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值