Javascript 暂停自动滚动Div
我有一个div,我想在页面加载时上下滚动,当用户悬停在div上时暂停滚动。我已经设法使div上下滚动,但我无法使其暂停 有什么建议吗Javascript 暂停自动滚动Div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个div,我想在页面加载时上下滚动,当用户悬停在div上时暂停滚动。我已经设法使div上下滚动,但我无法使其暂停 有什么建议吗 <div id="box" class="timeline container" style="overflow:scroll; width:100%; height:300px;"> //CONTENT </div> <script> $("#box").animate({ scro
<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>
//内容
$(“#box”).animate({scrollTop:$(document.height()},4000);
setTimeout(函数(){
$('#box')。动画({scrollTop:0},4000);
},4000);
setInterval(函数(){
$(“#box”).animate({scrollTop:$(document.height()},4000);
setTimeout(函数(){
$('#box')。动画({scrollTop:0},4000);
},4000);
},8000);
我建议您不要将动画用于滚动功能。相反,只需每隔100ms(或任何时间)增加滚动位置
您还需要添加标志以确定滚动方向和暂停状态:
// 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);
您应该能够使用jQuery函数停止/暂停动画
stop()
:您好,我刚刚尝试过这个功能,但div似乎根本没有滚动。@Mehul:我刚刚添加了一个JSFIDLE,显示它正在工作。您好,谢谢!我如何让它也向上滚动,并可能隐藏滚动条?刚刚再次检查,当我将它插入html脚本时,它似乎不起作用。@Mehul:那么,也许你应该在问题中输入真正的代码,并且overflow:hidden代码>将隐藏滚动条
$('#box').hover(
function() {
isPaused = true;
}, function() {
isPaused = false;
}
);