Is there a way to apply multiple CSS styles in a batch to avoid multiple reflows?

前端 未结 5 903
别跟我提以往
别跟我提以往 2020-12-30 05:56

I know that altering element\'s style via JavaScript directly will cause a reflow. However, I was wondering if it is possible to alter multiple style values in a batch with

相关标签:
5条回答
  • 2020-12-30 06:33

    Not directly but there are some good suggestions on minimising the impact of reflows here:

    http://dev.opera.com/articles/view/efficient-javascript/?page=3

    In short, try something like this:

    The second approach is to define a new style attribute for the element, instead of assigning styles one by one. Most often this is suited to dynamic changes such as animations, where the new styles cannot be known in advance. This is done using either the cssText property of the style object, or by using setAttribute. Internet Explorer does not allow the second version, and needs the first. Some older browsers, including Opera 8, need the second approach, and do not understand the first. So the easy way is to check if the first version is supported and use that, then fall back to the second if not.

    var posElem = document.getElementById('animation');
    var newStyle = 'background: ' + newBack + ';' +
      'color: ' + newColor + ';' +
      'border: ' + newBorder + ';';
    if( typeof( posElem.style.cssText ) != 'undefined' ) {
      posElem.style.cssText = newStyle; // Use += to preserve existing styles
    } else {
      posElem.setAttribute('style',newStyle);
    }
    
    0 讨论(0)
  • 2020-12-30 06:38

    You could set the element's visibility to 'hidden', then apply the styles and then make it visible again.

    0 讨论(0)
  • 2020-12-30 06:42

    You could put all the styles in a CSS class

    .foo { background:#000; color:#fff; ... }
    

    and then assign it to the className property

    // javascript
    var your_node = document.getElementById('node_id');
    your_node.className = 'foo'
    

    That should trigger only one repaint/reflow

    0 讨论(0)
  • 2020-12-30 06:43

    use:

    document.getElementById('elemnt_ID').setAttribute('style','color:white; margin:5px;');
    
    0 讨论(0)
  • 2020-12-30 06:47

    If you were using jQuery, it has a .css function that allows you to add multiple style at once:

    $('element').css({'color':'red', 'border':'#555 solid thin'});

    0 讨论(0)
提交回复
热议问题