javascript - 鼠标悬停时暂停 Jquery 脚本

标签 javascript jquery mouseover ticker news-ticker

我使用这个小代码片段作为 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/

相关文章:

javascript - jQuery.mouseover 从嵌套元素而不是附加监听器的元素返回事件

javascript - IE 中的页面加载时,动画 gif 不会显示动画

javascript - Knockout - 我想在列表加载到下拉列表后设置一个下拉列表的值,不仅仅是通过 id,而是作为对象

html - 如何突出显示一列中的所有文本?

jQuery mouseleave 来自子元素

JavaScript:设置鼠标悬停时CSS更改的方向?

javascript - 无法将功能绑定(bind)到按钮单击

javascript - CSS/cut an img's width when reducing the screen/window width 减少屏幕/窗口宽度

javascript - 如何将逗号分隔值分解为 <tr>

jquery 函数与 Ajax 在 Chrome 和 Opera 中失败