使用JavaScript动态应用CSS [英] Apply CSS dynamically with JavaScript

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

问题描述

采用JavaScript动态地将样式(即样式的值在运行时创建)应用于HTML元素的一种好方法是什么?

我正在寻找一种将JavaScript小部件(JS,CSS和标记)打包在单个组件(基本上是一个对象)中的方法。这个想法是让组件封装样式(因此用户拥有一个不错的API来修改样式,而不是直接修改CSS并间接应用更改的更紧密耦合的方法)。问题在于,单个API调用可能意味着更改了多个样式元素。

I'm looking for a way to package a JavaScript widget (JS, CSS and markup) in a single component (basically, an object). The idea would be for the component to encapsulate styling (so users have a nice API to modify it instead of a more tightly coupled approach of modifying the CSS directly and having changes applied indirectly). The problem is that a single API call might imply changes to several styling elements.

我要做的方法是构造CSS并将 style 属性设置为适当的元素(大多数可能会使用该ID以避免将更改应用于标记的其他区域)。这是一个好的解决方案吗?有更好的方法吗?

The way I would do it is to construct the CSS and set thestyle atrribute to the proper elements (most likely using the ID to avoid applying changes to other areas of the markup). Is this a good solution? Is there a better way to do it?

推荐答案

使用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.

这篇关于使用JavaScript动态应用CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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