2

最近我一直在阅读有关 jQuery 优化技巧的文章,这些技巧无疑有助于提高我的脚本的性能。

但是,我在我的网站上有这个精选新闻部分,鼠标悬停时可以将更多信息滑入适当的位置,并且该部分在除 Safari 之外的任何浏览器中都表现不佳(那么可能还有 Chrome。)

我相信这样做的原因是它在动画之前对每个 mouseover/mouseout 事件进行了相当多的 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});
});

由于我正在开发的网站尚未发布,因此我上传了新闻部分的屏幕截图,让您了解它的外观。

谢谢!

4

3 回答 3

2

对于初学者,可以进行Common subexpression Elimination,例如,而不是调用

$(this)

多次,将该对象存储在一个变量中并改用该变量。

var current = $(this);

另一方面,可以内联一次性使用的变量。有些人可能会称它们为过早优化,但既然已经说明代码很慢,我认为这还不算过早。

那里似乎没有使用 bottomOrSide 变量。

至于选择器,可以用这个代替整个长的东西吗?

$('.featuredBox')
于 2009-10-07T09:01:38.977 回答
2

另一种解决方案是记住所有计算。

不要直接调用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);
  });
}

这个解决方案会使我之前的答案有些没有意义(尽管仍然适用,但它们并不重要)。不过,请记住配置文件。

于 2009-10-07T09:42:30.057 回答
1

你重复做一些工作,这会伤害你。多少很难说,但试试这个...

var el = $(this);
var vid = $(".videoCaption", this);
// use el.blar() instead of $(this) and vid.blar() instead of $(".videoCaption", this).blar()

看起来您的 dom 结构在使用此面板的所有不同位置都必须不同,因为您的代码似乎必须做一些工作才能找到要使用的适当 dom 位。如果可能,我建议在所有不同位置使 DOM 结构相同,然后在代码中使用该结构。

如果这不可能,请尝试为每个位置编写此函数的唯一版本 - 不理想,但如果它解决了您的性能问题,它可能是值得的。

于 2009-10-07T08:57:28.220 回答