我正在尝试创建一个自动水平滚动页面,并且发现了previous post,该页面已经有所帮助。
唯一的事情是我希望用户能够与滚动条进行交互,因此如果抓住了滚动条,则可以有效地终止自动化。
function animatethis(targetElement, speed) {
var scrollWidth = $(targetElement).get(0).scrollWidth;
var clientWidth = $(targetElement).get(0).clientWidth;
$(targetElement).animate({
scrollLeft: scrollWidth - clientWidth
}, {
duration: speed,
complete: function() {
targetElement.animate({
scrollLeft: 0
}, {
duration: speed,
complete: function() {
animatethis(targetElement, speed);
}
});
}
});
};
animatethis($('#q1'), 5000);
#q1 {
white-space: nowrap;
overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="q1">((BEGIN)) Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me
Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me ((END))</div>
也在fiddle
中答案 0 :(得分:0)
我将代码更改为
function animatethis(targetElement, speed) {
var scrollWidth = $(targetElement).get(0).scrollWidth;
var clientWidth = $(targetElement).get(0).clientWidth;
// This code is added
$(targetElement).click(function() {
$(targetElement).stop();
});
$(targetElement).animate({
scrollLeft: scrollWidth - clientWidth
}, {
duration: speed,
complete: function() {
targetElement.animate({
scrollLeft: 0
}, {
duration: speed,
complete: function() {
animatethis(targetElement, speed);
}
});
}
});
};
animatethis($('#q1'), 10000);
#q1 {
padding: 10px;
white-space: nowrap;
overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="q1">((BEGIN)) Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me
Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me Watch me ((END))</div>
答案 1 :(得分:0)
您可以尝试用这种方法,每当抓住滚动条时它就会停止div滚动,并在离开时从其停止的地方再次开始滚动。看到这里:https://codepen.io/varunraval/pen/ydBgOG
fence