暂停自动滚动Div [英] Pause Auto-scrolling Div
问题描述
我有一个div,我想在页面加载时上下滚动,并在用户将鼠标悬停在div上时暂停滚动.我设法使div上下滚动,但是我无法使其暂停.
I have a div which I want to scroll up and down on page load and pause scrolling once the user hovers over the div. I have managed to get the div to scroll up and down however I cannot get it to pause.
有什么建议吗?
<div id="box" class="timeline container" style="overflow:scroll; width:100%; height:300px;">
//CONTENT
</div>
<script>
$("#box").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('#box').animate({scrollTop:0}, 4000);
},4000);
setInterval(function(){
$("#box").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('#box').animate({scrollTop:0}, 4000);
},4000);
},8000);
</script>
推荐答案
我建议您不要将动画用于滚动功能.相反,只需每100毫秒(或其他时间)增加滚动位置即可.
I would suggest you don't use animate for the scroll feature. Instead just increment the scroll position every 100ms (or whatever).
您还需要添加标志以确定滚动方向和暂停状态:
You also need to add flags to determine scroll direction and pause state:
// global level variables.
var isPaused = false;
var direction = 1;
var element = $('#box');
// interval for scroll.
setInterval(function () {
if(!isPaused){
var pos = element.scrollTop();
var offset = 1 * direction;
element.scrollTop(pos + offset);
// Change the scroll direction when hit an end.
if ((element[0].scrollHeight - element.scrollTop() == element.outerHeight()) || (element.scrollTop() <= 0)) {
direction *= -1;
}
}
}, 100);
然后,当发生mouseenter和mouseexit事件时,可以更改isPaused
标志,或者使用JQuery hover
事件:
Then you can change the isPaused
flag when on mouseenter and mouseexit events, or use JQuery hover
event:
$('#box').hover(
function() {
isPaused = true;
}, function() {
isPaused = false;
}
);
这篇关于暂停自动滚动Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!