提问人:mike36 提问时间:6/18/2023 最后编辑:Sai Manojmike36 更新时间:7/2/2023 访问量:58
Javascript 自动滚动
Javascript Auto Scrolling
问:
我想让这个自动滚动代码在到达底部时返回,并继续上下循环。还想添加鼠标悬停效果以暂停它。任何帮助都会很棒。
var interval = setInterval(() => {
if ($("#div1").scrollTop() != $('#div1')[0].scrollHeight)
$("#div1").scrollTop($("#div1").scrollTop() + 10);
else clearInterval(interval);
}, 1000);
#div1 {
height: 100px;
width: 200px;
border: 1px solid #ccc;
overflow: auto;
}
<div id="div1">
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
</div>
答:
0赞
Sai Manoj
7/2/2023
#1
该函数最初在 document.ready 上调用。它首先检索 div 元素的必要维度(divHeight 和 scrollHeight)。如果设置为,则表示向下滚动,反之亦然。要暂停和取消暂停,您可以在 jQuery 中使用 和 。以下是工作片段startScroll()
scrollDirection
1
-1
mouseenter
mouseleave
var scrollAmount = 1;
var scrollSpeed = 5000;
var scrollDirection = 1;
var paused = false;
var isMouseOver = false;
var scrollTimeout;
function startScroll() {
var div1 = $('#div1');
var divHeight = div1.height();
var scrollHeight = div1.prop('scrollHeight');
if (!paused && !isMouseOver) {
if (scrollDirection === 1) {
div1.animate({ scrollTop: scrollHeight }, scrollSpeed, function() {
div1.scrollTop(0);
startScroll();
});
} else {
div1.animate({ scrollTop: 0 }, scrollSpeed, function() {
div1.scrollTop(scrollHeight);
startScroll();
});
}
}
}
$(document).ready(function() {
startScroll();
$('#div1').mouseenter(function() {
isMouseOver = true;
paused = true;
$('#div1').stop();
});
$('#div1').mouseleave(function() {
isMouseOver = false;
paused = false;
startScroll();
});
});
#div1 {
height: 100px;
width: 200px;
border: 1px solid #ccc;
overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
This is a DIV<br>
</div>
评论