悬停时的连续动画(性能) [英] Continuous animation on hover (performance)
本文介绍了悬停时的连续动画(性能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个jQuery函数,通过减少元素的左边距来滚动DIV。它有效,但速度非常慢。它立刻吃掉了100%的CPU:s
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);
}
);
显然我每8ms运行一次这个函数,这是很多问题。我已经缓存了我的选择器,所以我不知道我能做些什么来提高性能。我只是错误的方式吗?
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?
推荐答案
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。
This is really simple without the setInterval or even setTimeout.
- 唯一重要的是知道
.animate()
接受函数回调,非常适合我们创建循环函数的目的。确保使用线性
缓动而不是默认的'swing'来使我们的循环保持不变。 - 要停止我们的动画,我们可以使用
stop()
来阻止动画构建。 - 只需创建2个函数并在
hover <中使用它们/ code>方法。
- The only important thing is to know that
.animate()
accepts a function callback, ideal for our purpose to create loop a function. Make sure to use thelinear
easing instead of the default 'swing' to make our loop constant. - To stop our animations we can use
stop()
to prevent animation buildups. - Simply create 2 functions and use them in your
hover
method.
并使用jQuery切换播放/暂停类:
and toggling play/pause classes using 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>
这篇关于悬停时的连续动画(性能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文