如图右侧黑色滚动条. 让滚动条自动滚动的效果
HTML
<div id="ptwarn">
<div class="warnMsg">
内容
</div>
</div>
JS
window.onload = function(params) {
setTimeout(function() {
autoScroll('#ptwarn','.warnMsg') //参数1是 需要上下移动内容的父元素 参数2 是 该父元素下的每个子元素; 参考上面的html即可
}, 1000);
}
function autoScroll(father,children) {
let isreset = false,
scrollItem = $(father), //需要上下移动内容的父元素
scrollItemchildren = 50, //每次移动的距离
scrollTimeTnterval = 2000, //滚动间隔, 单位毫秒 必须大于下面的 滚动动画的持续时间(超过的多一点好) !!!!!! 否则会越滚越慢 ( $(father).scrollTop() 会慢慢变小的BUG )
scrollAnimateTime = 1500, //滚动动画的持续时间, 毫秒
istoBottom = true,
innerHeight = $(father).innerHeight();
function time() {
if (isreset) {
isreset = false;
return
}
let a = scrollItem.scrollTop();
// console.log(a,scrollItemchildren,scroll,istoBottom)
if (istoBottom) {
scrollItem.animate({
scrollTop: a + scrollItemchildren
}, scrollAnimateTime,'linear'); //滚动动画时间
} else {
scrollItem.animate({
scrollTop: a - scrollItemchildren
}, scrollAnimateTime,'linear'); //滚动动画时间
}
if (istoBottom) {
if(scrollItem.scrollTop() + innerHeight >= $(father).prop("scrollHeight")){
// console.log('到底了',scrollItem.scrollTop())
isreset = true;
istoBottom = false;
}
} else {
if (scrollItem.scrollTop() <= 0) {
// console.log('到顶了',scrollItem.scrollTop())
istoBottom = true;
}
}
}
let sItval = setInterval(time, scrollTimeTnterval); //多久滚动一次
// 下面这个有BUG , 等我有空在修复, 鼠标移上去会让定时器变快
// scrollItem.mouseenter(function(a) {
// sItval = clearInterval(sItval);
// })
// scrollItem.mouseleave(function(a) {
// clearInterval(sItval);
// sItval = setInterval(time, 800);
// })
}