简体   繁体   中英

Best practice for manipulating CSS from JavaScript?

Today I encountered a problem when a rogue z-index property caused problems. Ok, it happens, but the problem was finding the place where it was declared. Browser shows inline style, but in markup it's empty, searching solution wide for z-index: 1001 also gave nothing.

Finally I found it in some JavaScript

        $("#header").css({
          //other props
          "z-index": "1001"
        });

This gave me some ideas about how it should be done, but I'm not sure.

The Question:

Is it better to change CSS from JavaScript prop by prop or make multiple CSS classes and change elements class from JS?

I am inclined to use multiple classes, but another option is welcomed.

I would advise just using the addClass and removeClass methods in jQuery. This way your JavaScript can be responsible for controlling behavior and your CSS remains responsible for the styling.

eg in your css:

.some-class {
    z-index:1001;
}

in your JavaScript:

$("#header").addClass('some-class');
//or 
$("#header").removeClass('some-class');

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