文字横向滚动(无滚动条,速度可控)

当滚动条去除失败时
注意:父盒子要设固定高,且内容能滚动(例如:overflow-x: scroll;)

一、用css动画实现

1、html
	<div class="scr"><span>呵呵哈哈哈呵呵哈哈哈呵呵哈哈哈呵呵哈哈哈</span></div>
2、css

1)给父盒子一个宽度
2)父盒子开启不换行
3)父盒子overflow-x: scroll;

	.scr {
	  height: 60px;
	  width: 200px;
	  line-height: 60px;
	  border: 1px solid red;
	  margin-left: 100px;
	
	  white-space: nowrap;
	  overflow-x: scroll;
	  overflow-y: hidden;
	}
	/* 去除滚动条 (宽或高固定,overflow取值scroll或auto)*/
	.scr::-webkit-scrollbar {
	  display: none;
	}
	/* 子盒子内容自动滚动 */
	@keyframes rule {
	  0% {left: -10px}
	  100% {left: -200px}
	}
	span {
	  position: relative;
	  animation-name: rule;
	  animation-iteration-count: infinite;
	  animation-timing-function: linear;
	  animation-duration: 4s;
	}

二、拓展: 用js实现(比较容易控制速度和位置)(vue语法)

js实现文字滚动,滚动到最后一个字暂停5秒,重新开始滚动。

1.html
<div ref="rollingBox" class="rolling_box">
  <div ref="rollingBar" class="scroll_text" v-if="scrollText">{{scrollText}}</div>
</div>
2.css
.rolling_box {
  overflow: hidden;
  height: 60px;
  position: relative;
  background-color: pink;
  
  .scroll_text {
    position: absolute;
    width: auto;
    height: 60px;
    line-height: 60px;
    color: red;
    padding: 0 20px;
    white-space: nowrap;
  }
}
3.js
export default {
  data () {
    return {
	  scrollText: '', // 滚动文字
      requestId: '', // 滚动动画id
      isFirst: true, // 是否是第一次
      scrollTextWidth: null // 滚动距离
	}
  },
  watch: {
    scrollText(val) {
      window.requestAnimationFrame(this.scroll(0))
    }
  },
  methods: {
	scroll(value) {
      return () => {
        // 实例销毁退出
        if (this.isDestroyed()) return
        if (!this.$refs.rollingBar) return
        let a = this.$refs.rollingBar['clientWidth']
        let b = this.$refs.rollingBox['clientWidth']
        if (this.isFirst) {
          this.scrollTextWidth = b - a // 初始化要滚动的距离
          value = b // 初始化开始的位置
          console.log('==========(要滚动的距离 scrollTextWidth)========>>>', this.scrollTextWidth)
        }
        // 到最后一个字暂停5秒
        if (value <= this.scrollTextWidth && !this.isFirst ) {
          window.cancelAnimationFrame(this.requestId)
          setTimeout(() => {
            value = b // 暂停后初始化开始位置
            value -= 2 // 速度
            this.$refs.rollingBar.style.marginLeft = `${value}px`
            this.requestId = window.requestAnimationFrame(this.scroll(value))
          }, 5000)
        } else {
          this.isFirst = false
          value -= 2
          this.$refs.rollingBar.style.marginLeft = `${value}px`
          this.requestId = window.requestAnimationFrame(this.scroll(value))
        }
      }
    },
    isDestroyed() {
      return !this.$el
    },
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值