7

I've created a jQuery function that scrolls a DIV by decreasing the left-margin of the element. It works, but it's incredibly slow. It eats up 100% CPU in no time :s

$(".scroll").hover(
    function () {
        var scroll_offset = parseInt($('#content').css('margin-left'));
        sliderInt = self.setInterval(function(){
            $content.css({'margin-left':scroll_offset+'px'});
            scroll_offset--;
        },8);
    }, 
    function () {
        clearInterval(sliderInt);
    }
);

Obviously I am running this function every 8ms, which is asking a lot. I'm already cacheing my selectors, so I don't know what I can do to improve performance. Am I just going about it the wrong way?

4

2 回答 2

24

function play () {
  $('#ball').animate({left: '+=20'}, 100, 'linear', play);
}

function pause () {
  $('#ball').stop();
}

$("#bar").hover( play, pause );
#bar {
  margin-top: 20px;
  background: #444;
  height: 20px;
}
#bar:hover #ball {
  background: lightgreen;
}

#ball {
  position: relative;
  left: 0;
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}
<div id="bar">
  <div id="ball"></div>
</div>

<script src="//code.jquery.com/jquery-3.1.0.js"></script>

如果没有 setInterval 甚至 setTimeout,这真的很简单。

  • 唯一重要的是要知道.animate()接受函数回调,非常适合我们创建循环函数的目的。确保使用linear缓动而不是默认的“摆动”来使我们的循环保持不变。
  • 要停止我们的动画,我们可以使用它stop()来防止动画堆积。
  • 只需创建 2 个函数并在您的hover方法中使用它们。

使用 CSS3

并使用 jQuery 切换播放/暂停类:

function play() {
  $('#ball').addClass("play").removeClass("pause");
}

function pause() {
  $('#ball').addClass("pause"); // don't remove .play here
}

$("#bar").hover(play, pause);
#bar {
  margin-top: 20px;
  background: #444;
  height: 20px;
}
#bar:hover #ball {
  background: lightgreen;
}
#ball {
  position: relative;
  left: 0;
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}

.play {
  animation: ball-anim 5s infinite linear;
}
.pause {
  animation-play-state: paused;
}
@keyframes ball-anim {
  0%   { left: 0; }
  50%  { left: calc(100% - 20px); }
  100% { left: 0; }
}
<div id="bar">
  <div id="ball"></div>
</div>

<script src="//code.jquery.com/jquery-3.1.0.js"></script>

于 2012-04-19T00:35:07.983 回答
1

.animate()是一个很好的方法。例子:

$(".scroll").hover(function(){
  $("#content").animate({
    marginLeft: "100px",
  }, 1500 );
});​

工作演示

阅读文档以了解如何使用它。

于 2012-04-18T23:44:28.470 回答