从JavaScript处理CSS的最佳做法? [英] Best practice for manipulating CSS from JavaScript?

查看:79
本文介绍了从JavaScript处理CSS的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,当流氓z-index属性引起问题时,我遇到了一个问题.好的,它确实发生了,但是问题是找到了声明它的地方. 浏览器显示内联样式,但在标记中为空,在整个解决方案中搜索z-index: 1001也没有任何效果.

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.

最后我在一些JavaScript中找到了它

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.

问题:

是从JavaScript道具逐个更改CSS还是从JS创建多个CSS类并更改元素类更好?

我倾向于使用多个类,但欢迎使用另一个选择.

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

推荐答案

我建议仅使用 addClass 和 removeClass 方法.这样,您的JavaScript可以负责控制行为,而CSS则负责样式.

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.

例如在您的CSS中:

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

在您的JavaScript中:

in your JavaScript:

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

这篇关于从JavaScript处理CSS的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆