写此文背景: 在通过goole/百度搜索之后,实现此效果的示例确实很多,但是拿到自己项目中,就是太适用(可能滚着滚着滚偏了),因此琢磨了好久,写了该组件,肯定也有各种问题,所以分享出来让大家路过的顺便提一嘴,我好改之...
/**
* desc: 单条向上无缝滚动
*/
import Vue from "vue";
Vue.directive('newscroll', {
bind(el, binding, vnode) {
// 进行一次性初始化设置
console.log('bind')
},
inseted (el, binding, vnode) {
console.log('inseted')
},
update(el, binding, vnode) {
console.log('update')
let sel = el, //该滚动元素
die_h= binding.value.oH; // 固定死的高度
let step = 0, // 一小步的距离
timer_b = null, // 循环每个li
timer_s = null; // 一个li循环高度++
if (binding.oldValue.oH != binding.value.oH) {
console.log('只调用一次')
if (timer_b) clearTimeout(timer_b)
cycle()
}
function cycle () {
if (timer_b) clearTimeout(timer_b)
timer_b = setTimeout(function () {
scroll()
}, 2000)
}
function scroll () {
cancelAnimationFrame(timer_s);
timer_s = requestAnimationFrame(function fn () {
if (Math.abs(step) >= die_h) {
cancelAnimationFrame(timer_s);
step = 0
sel.style.marginTop = 0
sel.appendChild(sel.firstChild)
cycle()
} else {
step--
sel.style.marginTop = `${step}px`
timer_s = requestAnimationFrame(fn)
}
})
}
},
componentUpdated () {
console.log('组件更新完成')
},
unbind () {
console.log('解绑')
}
});
复制代码
使用方法:
- 新建一个名为 v-newscroll.js的文件
- 把以上代码复制进去
- 将该文件放入到一个你认为合适的目录下
- 在你要使用该指令的组件中应用
<template>
<div class="scroll-wrap" ref="wrap">
<span class="scroll-title">新闻: </span>
<ul v-newscroll="{ oH }" class="list">
<li v-for="(item, index) in list" :key="index">{{item}}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'scroll2',
data () {
return {
list: [
"1—— javascript",
"2—— html",
"3—— vue"
],
oH: 0,
}
},
mounted () {
this.oH = this.$refs.wrap.offsetHeight;
},
directives: {
"v-newscroll": require('../_common/directives/v-newscroll.js')
}
}
</script>
<style lang="scss">
ul, li {
list-style: none;
}
.scroll-wrap {
border: 1px solid red;
height: 60px;
overflow: hidden;
display: flex;
background: lightcoral;
color: #fff;
box-sizing: border-box;
}
.scroll-title {
line-height: 60px;
background: #000;
padding: 0 20px;
}
.list {
margin-left: 20px;
li {
line-height: 60px;
height: 60px;
}
}
</style>
复制代码
好了,尝试一下吧!
我之所以分享出来,是想让各位大大给指正一下,我可以优化或者采取大大们的方案完成这个指令的编写,在此,先谢过啦~
初来乍到,不喜勿喷!