简体   繁体   中英

Updating CSS Values in Javascript across multiple elements in batch?

I have a web app I'm working on that requires frequent updates to CSS values across multiple elements. I'm trying to reduce reflow and was wondering if there is a way to accomplish this in batch? Here's an example:

for(let j = 0; j<defholdids.length; j++) {
    $('#'+defholdids[j]).css({
      'z-index':'4',
      'color':'rgba(0,0,0,0.7)',
    });

defholdids is an array with the element ID's stored. The loop iterates through and updates the css values. To my understanding, a reflow is triggered each time an element css value is updated. Is there a way to update the CSS values across all the elements AND THEN 'reflow' rather than triggering a 'reflow' each iteration?

I'm working with Electron to create a desktop app, not sure if that makes a difference.

How about assigning one class name for the elements that require cssupdates and update them at once. For example

   $('.class-name-goes-here').css({
      'z-index':'4',
      'color':'rgba(0,0,0,0.7)',
    });

You're nearly always better off by introducing a (second) class then adding/toggling/removing that class on the appropriate element(s), instead of directly manipulating the .css() of elements.

In Joseph's answer he introduces .class-name-goes-here (which I'll shorten to .main-class
If you introduce a second/additional class:

.aux-class {
  z-index:4;
  color: rgba(0,0,0,0.7);
}

you can do $('.main-class').addClass('aux-class');
This would apply the change to all of the .main-class elements all at once.

You can change it back later just by $('.main-class').removeClass('aux-class');

If you have well-known & well-maintained state you can use .toggleClass() instead of separate adds and removes.

This doesn't prevent you from doing further manipulations with $(element).css() but those changes would have to be reverted "manually". I would probably introduce another different (third? fourth?) class instead.

It's also good to name the class for the state (or object) it represents.
Those names depend on what the things are and what you're doing with them. Maybe instead of .main-class and .aux-class good names could be .toggleable and .active , so possibly

<section>
  <div class="toggleable">
    ...some content...
  </div>

  <div class="something-else">
    ...some other content...
  </div>

  <div class="toggleable">
    ...even more content...
  </div>

  <div>
    ...no particular class on this div...
  </div>
</section>

Then, on a button press (for example) you would do
$('.toggleable').addClass('active')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM