我创建了一个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);
}
);
Run Code Online (Sandbox Code Playgroud)
显然我每隔8ms运行一次这个功能,这是很多问题.我已经缓存了我的选择器,所以我不知道我能做些什么来提高性能.我只是走错了路吗?
Rok*_*jan 25
function play () {
$('#ball').animate({left: '+=20'}, 100, 'linear', play);
}
function pause () {
$('#ball').stop();
}
$("#bar").hover( play, pause );Run Code Online (Sandbox Code Playgroud)
#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%;
}Run Code Online (Sandbox Code Playgroud)
<div id="bar">
<div id="ball"></div>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>Run Code Online (Sandbox Code Playgroud)
没有setInterval甚至setTimeout,这非常简单.
.animate()接受函数回调,非常适合我们创建循环函数的目的.确保使用linear缓动而不是默认的'swing'来使循环保持不变.stop()用来防止动画构建.hover方法中使用它们.并使用jQuery切换播放/暂停类:
function play() {
$('#ball').addClass("play").removeClass("pause");
}
function pause() {
$('#ball').addClass("pause"); // don't remove .play here
}
$("#bar").hover(play, pause);Run Code Online (Sandbox Code Playgroud)
#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; }
}Run Code Online (Sandbox Code Playgroud)
<div id="bar">
<div id="ball"></div>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>Run Code Online (Sandbox Code Playgroud)