[英]Getting the real width with $(this).scrollWidth is very slow
我正在休息
$('.Row .Cell .Text').each(function (index, item) {
if (this.scrollWidth > $(this).parent().width())
$(this).next().show();
else $(this).next().hide();
});
當我沒有分配$('。Row .Cell .Text')時,一切都很好。 但如果我有分配行和單元格,上面的代碼,特別是
this.scrollWidth
花了很多時間。
知道我怎么能得到同樣的東西,但更快?
添加了一個小提琴jsFiddle
似乎大部分性能影響實際上來自於此:
$(本)。接下來()隱藏()。
起初我認為你可能會受到性能打擊,因為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);
我猜你正試圖隱藏.Icon
的if .Text
width> .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/
使用此比較器,您可以將Brandon的答案加速大約6次
if (this.scrollWidth > this.parentNode.scrollWidth)
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.