使用$(this)获取实际宽度.scrollWidth非常慢

Getting the real width with $(this).scrollWidth is very slow

本文关键字:scrollWidth 非常 this 获取 使用      更新时间:2023-09-26

我正在做以下事情

$('.Row .Cell .Text').each(function (index, item) {
                if (this.scrollWidth > $(this).parent().width())
                    $(this).next().show();
                else $(this).next().hide();
});

一切都是好的,当我没有分配$('。行。单元格。文本')。但是如果我有很多行和单元格,上面的代码特别是

this.scrollWidth

占用大量时间。

我怎么能得到同样的东西,但更快吗?

添加了一个小提琴jsFiddle

我猜你正试图隐藏.Icon.Text宽度> .Cell。参见下面的方法,

我试图通过使用filter来移动jQuery代码。

CSS

/*set overflow for .Text - This lets you calculate the actual width of .Text*/
.Text { overflow: hidden; } 
/* Hide .Icon by default and show only if .Text width < .Cell width*/
.Cell .Icon { display: none; }

JS

$('.Row .Cell .Text').filter(function (i, el) {    
    return el.scrollWidth <= this.parentNode.scrollWidth; //Thanks @nicoabie
}).next().show();
演示:

http://jsfiddle.net/nYSDy/4/

似乎大部分性能损失实际上来自于:

$ () . next () hide ();

起初我认为你可能会采取性能打击,因为如何jquery可能会处理额外的文本节点创建的空格元素之间,所以我尝试:

this.nextSibling.nextSibling.style。Display = 'none';

这并没有真正帮助问题,所以似乎简单地在这么多元素上设置样式是非常缓慢的。为了解决这个问题,您可以考虑将默认样式设置为最常见的情况,然后只对其他情况作出反应。对于您发布的小提琴示例,这将导致:

CSS:

.Icons {
  display: none;
}
新JS:

$('.Row .Cell .Text').each(function (index, item) {
                if (this.scrollWidth > $(this).parent().width())
                    $(this).next().show();
});

附录:事实证明,为所有这些元素添加一个类会更快一些所以你可以这样做http://jsfiddle.net/XuhaT/1/:

CSS:

#vTable {
    width:800px;
}
.Icon {
    display: none;
}
.visible.Icon {
    display: block;
}

JS:

$("#countOfItems").html($('#vTable .Row ').length);
var startDate = new Date();
$('.Row .Cell .Text ').each(function (index, item) {
    if (this.scrollWidth > $(this).parent().width()) $(this).next().addClass('visible');
});
var endDate = new Date();
$("#claculationTime").html(endDate - startDate);

使用这个比较器可以将Brandon的回答速度提高大约6倍

if (this.scrollWidth > this.parentNode.scrollWidth)

希望有帮助!