我需要在重新排序或删除一个项目后更改列表中的每个项目的颜色,现在我使用jquery的css方法,如下所示
$('li').css('background-color', color);
它工作,但非常慢,有时页面会错误地呈现颜色,即使在Chrome上也应该很快 . 该列表没有很多项目,低于10,通常是5-7 . 所以这种表现是不可接受的 . 所以我想知道在CSS3或HTML5中是否有更好,更快的方式 . 如果没有,如果有一个walkaround或某种jquery解决方案?
刷新列表项颜色的代码如下 . 索引可以由函数决定,颜色可以由它决定颜色 . 我认为的主要问题是改变背景颜色会触发回流或重新渲染 .
function refreshListItemColor(liElements, colorGetter, indexGetter) {
colorGetter = colorGetter || (function (color) {
return color;
});
indexGetter = indexGetter || (function (liElement, index) {
return index;
});
liElements.each(function (index, liElement) {
index = indexGetter(liElement, index);
var data = ko.dataFor(liElement);
var indexColor = colorForIndex(index);
indexColor = colorGetter(indexColor, data);
if (indexColor !== $(liElement).css('background-color')) {
$(liElement).css('background-color', indexColor);
}
});
}
Update :使用element.style ['background-color']赢得't do. The issue still remains. Another possible explanation for the lagging is that every list item itself has about 10 child elements, making change list item'的颜色特别贵 .
Update2 :我将尝试提出一个相关的问题:有没有办法改变父节点背景的颜色而不会触发子元素的重新渲染?
Update3 :我试图为每个换色操作添加延迟,如下所示
var delay = 100, step = 100;
liElements.each(function (index, liElement) {
index = indexGetter(liElement, index);
var data = ko.dataFor(liElement);
var indexColor = colorForIndex(index);
indexColor = colorGetter(indexColor, data);
if (indexColor !== $(liElement).css('background-color')) {
setTimeout(function () {
liElement.style['background-color'] = indexColor;
}, delay);
delay += step;
}
});
似乎可以缓解这个问题很多 . 我想这不会解决问题,但会将影响降低到可接受的水平 .