当滚动条去除失败时
注意:父盒子要设固定高,且内容能滚动(例如: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
},
}
}