首页 文章

在CSS3或HTML5中更改元素背景颜色的有效方法

提问于
浏览
0

我需要在重新排序或删除一个项目后更改列表中的每个项目的颜色,现在我使用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;
    }
});

似乎可以缓解这个问题很多 . 我想这不会解决问题,但会将影响降低到可接受的水平 .

6 回答

  • 1

    你能在样式表中使用attribute selectors吗?

    [data-row="1"][data-col="3"]{
        background-color: blue;
    }
    

    我注意到如果要选择整行或列,则必须使用 !important

    [data-col="3"]{
        background-color: blue !important;
    }
    

    css change


    (edit)Adding styles dynamically
    使用div创建一个空样式标记

    <style type="text/css" id="dynamicstyle"></style>
    

    并像其他标签一样附加到它上面

    $("#dynamicstyle").append('[data-row="0"]{background-color:red !important;}');
    

    对于您的情况,您可以检查何时添加元素并添加行样式,因为理论上用户可以堆积所有元素 .

    $(function () {
    var maxRows = 0;
    $("ul").bind("DOMSubtreeModified", updateStyleSheet);
    
    function updateStyleSheet() {
        var childCount = $("ul").children().length;
        if (maxRows < childCount) {
            maxRows = childCount;
            var newRule = [
                '[data-row="',
            maxRows,
                '"]{background-color:', ((maxRows % 2) ? "red" : "blue"),
                ' !important;}'].join('')
            $("#dynamicstyle").append(newRule);
        }
    }
    });
    

    http://jsfiddle.net/PgAJT/126/

    FizzBuzz行http://jsfiddle.net/PgAJT/127/

  • 1

    删除“if”,这可能会强制浏览器重绘/重新编译/重排最新的CSS值 .

    if (indexColor !== $(liElement).css('background-color')) {
    

    是的,读取速度很慢,因为它们会阻止写入组合 .

  • 2

    据推测,颜色由列表中元素的位置决定 .

    在样式表中使用nth-child or nth-of-type选择器 .

  • 1

    嗨,我刚试过wat你需要检查它..

    http://jsbin.com/awUWAMeN/7/edit

    function change()
    {
      var colors = ['green', 'red', 'purple'];
    alert(colors)
    $('.sd-list li').each(function(i) {
        var index = $(this).index();
    
            $(this).css('background-color', colors[index]);
    
    });
    
    }
    
  • 2

    我创建了一个包含10个列表项的简单测试,每个项目有12个子项,并且每次Gridster的draggable.stop事件触发时为每个项设置背景颜色 . 在IE11和Chrome中,这种变化几乎是即时的 .

    对我而言,这表明CSS渲染不是很慢,但可能是计算确定哪些颜色是哪些元素 .

    这是我使用的JavaScript:

    var colors = ['#000', '#001', '#002', '#003', '#004', '#005', '#006', '#007', '#008', '#009', '#00a', '#00b'];
    
    $('.gridster ul').gridster({
        widget_margins: [10, 10],
        widget_base_dimensions: [120, 120],
        draggable: {
            stop: function (e, ui, $widget) {
                refreshListItemColor();
            }
        }
    });
    
    function refreshListItemColor() {
        var sortedElements = [];
        $('ul > li:not(.preview-holder').each(function () {
            sortedElements.push([this, this.getAttribute('data-col'), this.getAttribute('data-row')]);
        });
    
        sortedElements.sort(function (a, b) {
            return a[1] - b[1] || a[2] - b[2];
        });
    
        for (var i = sortedElements.length - 1; i >= 0; i--) {
            sortedElements[i][0].style.backgroundColor = colors[i];
        }
    }
    

    你如何确定在每个列表项上设置哪些颜色?

  • 0

    我发现用你想要的css属性创建一个类很快,然后将该类添加到你想要应用css属性的dom元素中 . CSS规则无需刷新即可显示 .

    CSS:

    .bg-green{
    background:green;
    }
    

    JS:

    $("#someDomId").toggleClass('bg-green','add');
    

    处理列表的一种很酷的方法是在创建/修改它时索引每个列表元素的id:

    创建列表:

    for (i=0;i=m;i++){
    var listElement = "<li id='"+i+">Some Content</div>";
    $('ul').append(listElement);
    }
    

    然后,您可以运行另一个for循环并通过选择它的id来更改每个列表元素,而不是遍历dom元素(这是昂贵的) .

    for (i=0;i=m;i++){
    $("#"+i).toggleClass('bg-green','add');
    }
    

相关问题