且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript动态应用CSS

更新时间:2022-04-30 05:19:56

使用Jquery

使用css()函数将样式应用于现有元素,并在其中传递包含样式的对象:

Use the css() function to apply style to existing elements where you pass an object containing styles :

var styles = {
  backgroundColor : "#ddd",
  fontWeight: ""
};
$("#myId").css(styles);

您还可以同时使用以下一种样式:

You can also apply one style at the time with :

$("#myId").css("border-color", "#FFFFFF");

香草JS:

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

使用CSS:

您还可以使用单独的css文件,其中包含类内部所需的不同样式,并根据您在上下文中向元素添加或删除这些类的情况。

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

在您的CSS文件中,您可以使用

in your css file you can have classes like

.myClass {
    background-color: red;
}

.myOtherClass {
    background-color: blue;
}

再次使用jquery,向元素添加或删除类,您可以使用

Again using jquery, to add or remove a class to an element, you can use

$("#myDiv").addClass('myClass');

$("#myDiv").removeClass('myClass');

我认为这是一种更干净的方法,因为它将您的样式与您的逻辑分开。但是,如果css的值取决于服务器返回的值,则可能很难应用此解决方案。

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.