简体   繁体   English

从JavaScript处理CSS的最佳做法?

[英]Best practice for manipulating CSS from JavaScript?

Today I encountered a problem when a rogue z-index property caused problems. 今天,当流氓z-index属性引起问题时,我遇到了一个问题。 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. 浏览器显示内联样式,但在标记中为空,在解决方案中搜索z-index: 1001也没有给出任何内容。

Finally I found it in some JavaScript 最后我在一些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? 是通过prop来从JavaScript prop更改CSS还是从JS创建多个CSS类并更改元素类更好?

I am inclined to use multiple classes, but another option is welcomed. 我倾向于使用多个类,但是欢迎使用另一个选项。

I would advise just using the addClass and removeClass methods in jQuery. 我建议仅在jQuery中使用addClassremoveClass方法。 This way your JavaScript can be responsible for controlling behavior and your CSS remains responsible for the styling. 这样,您的JavaScript可以负责控制行为,而CSS则负责样式。

eg in your css: 例如在你的CSS:

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

in your JavaScript: 在您的JavaScript中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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