jquery - 优化 jQuery 悬停代码以实现更好的性能(更流畅的动画)

标签 jquery performance optimization hover jquery-animate

最近我花了一些时间阅读有关 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/

相关文章:

jquery - 如何使用node js通过mongodb获取多个文档并显示到html页面

performance - 回文 - 是否有可能使我的代码更快

python - 打印数字时添加千位分隔符

.net - Entity Framework 需要 3 秒钟来执行我在我生命中第一次看到的最简单的查询。之后变成瞬间

performance - 有哪些不同的技术可以使超形态调用站点更加高效

c++ - 并行计算的 C++ 代码优化示例

java - 优化两个列表的比较和合并

javascript - 如何创建一个函数来检测我的可滚动 tbody 何时溢出?

javascript - 仅从 jquery 选择中删除第一个元素

javascript - 需要 SelectBoxIt 和 ReactJS 支持