我使用这个小代码片段作为 jquery 新闻行情:
var speed = 5;
var items, scroller = $('#scroller');
var width = 0;
scroller.children().each(function(){
width += $(this).outerWidth(true);
});
scroller.css('width', width);
scroll();
function scroll(){
items = scroller.children();
var scrollWidth = items.eq(0).outerWidth();
scroller.animate({'left' : 0 - scrollWidth}, scrollWidth * 100 / speed, 'linear', changeFirst);
}
function changeFirst(){
scroller.append(items.eq(0).remove()).css('left', 0);
scroll();
}
我尝试在鼠标悬停时暂停脚本。
使用 stop() 函数,它可以工作,但每次我将鼠标移过时它都会失去速度。
我知道它们与宽度/距离/速度有关,但我无法纠正它。
这是完整的脚本:http://codepen.io/anon/pen/wBayyz
谢谢。
最佳答案
$(document).ready(function(){
var speed = 5;
var items, scroller = $('#scroller');
var width = 0;
scroller.children().each(function(){
width += $(this).outerWidth(true);
});
scroller.css('width', width);
scroll();
function scroll(){
items = scroller.children();
var scrollWidth = items.eq(0).outerWidth();
scroller.animate({'left' : (items.eq(0).offset().left - 39) - scrollWidth}, scrollWidth * 100 / speed, 'linear', changeFirst);
}
function changeFirst(){
scroller.append(items.eq(0).remove()).css('left', 0);
scroll();
}
$("#scroller").hover(function() {
$(this).stop();
}, function() {scroll();});
});
#scroller{height:100%;margin:0;padding:0;line-height:30px;position:relative;}
#scroller li{float:left;height:30px;padding:0 0 0 10px;list-style-position:inside;}
#scrollerWrapper{width: 500px; height:30px;margin:30px;overflow:hidden;border:1px #333 solid;background:#F2F2F2;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<title>Horizontal scroller</title>
</head>
<body>
<div id="scrollerWrapper">
<ul id="scroller">
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li> Maecenas sollicitudin, ante id ultrices consectetur.</li>
<li>Cum sociis natoque penatibus et magnis dis parturient. </li>
</ul>
</div>
</body>
</html>
问题是当您重新启动滚动时,您需要考虑已经滚动了多少内容,就像我在这里所做的那样。
这应该就是您要找的,
关于javascript - 鼠标悬停时暂停 Jquery 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151994/