我创建了一个 jQuery 函数,它通过减少元素的左边距来滚动 DIV。它有效,但速度非常慢。它会立即占用 100% 的 CPU :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);
}
);
显然我每 8 毫秒运行一次这个函数,这要求很高。我已经缓存了我的选择器,所以我不知道我能做些什么来提高性能。我是不是用错了方法?
最佳答案
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
缓动而不是默认的“swing”来使我们的循环保持不变。 - 要停止我们的动画,我们可以使用
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>
关于javascript - 悬停时的连续动画(性能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10219649/