最近我花了一些时间阅读有关 jQuery 优化技巧的文章,这无疑有助于提高我的脚本的性能。
但是,我的网站上有这个特色新闻部分,鼠标悬停时会将更多信息滑入到位,并且该部分在除 Safari 之外的任何浏览器中都表现不佳(可能还有 Chrome。)
我认为,这样做的原因是它在动画之前对每个鼠标悬停/鼠标移出事件进行了相当多的 DOM 遍历和计算。
我的问题很简单:有没有办法优化下面的代码,让动画运行得更流畅?
$('#featuredSide .featuredBox,#featuredBottom .featuredBox,#archiveVideos .featuredBox').hover(function(){
var boxHeight = parseInt($(this).css('height'))-8;
var bottomOrSide = $(this).parents("div[id^='featured']").attr("id")
var captionPos = 76;
var captionHeight = parseInt($(this).find(".videoCaption").css('height'));
var animateTo = boxHeight-captionHeight;
$(".videoCaption", this).stop().animate({top:animateTo + 'px'},{queue:false,duration:160});
}, function() {
$(".videoCaption", this).stop().animate({top:captionPos},{queue:false,duration:100});
});
由于我正在开发的网站尚未发布,所以我 uploaded a screenshot of the news section让您了解它的样子。
谢谢!
最佳答案
另一个解决方案是 memoize全部计算。
不要直接调用hover,使用“each”,计算,然后应用“hover”。
因此(我尝试尽可能少地更改代码):
$('#featuredSide .featuredBox,#featuredBottom .featuredBox,#archiveVideos .featuredBox').each(function(){
var boxHeight = parseInt($(this).css('height'))-8;
var bottomOrSide = $(this).parents("div[id^='featured']").attr("id")
var captionPos = 76;
var captionHeight = parseInt($(this).find(".videoCaption").css('height'));
var animateTo = boxHeight-captionHeight;
var params = {top:animateTo + 'px'};
var options = {queue:false,duration:160};
var target = $(".videoCaption", this);
$(this).hover(function () {
target.stop().animate(params, options);
});
}
这个解决方案将使我之前的答案有些无意义(它们并不重要,尽管仍然适用)。不过,请记住进行个人资料分析。
关于jquery - 优化 jQuery 悬停代码以实现更好的性能(更流畅的动画),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1530331/