如何在 JavaScript 中动态设置和修改 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10420606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically set and modify CSS in JavaScript?
提问by AkademiksQc
I have some JavaScript code that creates some div
elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css
file, I would like to set the CSS className
of my element and then dynamically inject some values into the defined CSS property.
我有一些 JavaScript 代码可以创建一些div
元素并设置它们的 CSS 属性。因为我想将 CSS 逻辑从我的 JavaScript 代码中分离出来,并且因为 CSS 在它自己的.css
文件中更容易阅读,所以我想设置className
我元素的 CSS ,然后动态地将一些值注入到定义的 CSS 属性中。
Here is what I would like to do :
这是我想做的:
style.css
:
style.css
:
.myClass {
width: $insertedFromJS
}
script.js
:
script.js
:
var myElement = document.createElement("div");
myElement.className = "myClass";
I want to do something like this but at that point myElement.style.width
is empty
我想做这样的事情,但那时myElement.style.width
是空的
myElement.style.width.replaceAll("$insertedFromJS", "400px");
I think my problem here is that after the call to myElement.className = "myClass"
, the CSS is not yet applied.
我认为我的问题是在调用 之后myElement.className = "myClass"
,CSS 尚未应用。
采纳答案by Mark Rawlingson
If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and thensave it back to the DOM. But that's a really overly-complicated way to go about doing something that...
如果我正确理解了您的问题,那么听起来您是在尝试在 css 文件中设置占位符文本,然后使用 javascript 解析出您要为该类设置的 css 值的文本。你不能以你试图做的方式做到这一点。为此,您必须从 dom 中获取 CSS 文件的内容,操作文本,然后将其保存回 DOM。但这是一种非常复杂的方式来做一些......
myElement.style.width = "400px";
...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a wholelot you can do about that. You're trying to set css dynamically, after all.
...可以在几秒钟内为您完成。我知道它并没有真正解决脱钩JS CSS的问题,但真正有没有一个整体很多你可以做的。毕竟,您正在尝试动态设置 css。
Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.
根据您要完成的任务,您可能想尝试定义多个类并仅更改 js 中的 className 属性。
回答by Starx
Setting the style, might be accomplished defining the inner-page style declaration.
设置样式,可以通过定义内页样式声明来完成。
Here is what i mean
这就是我的意思
var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.
然而,修改它的部分可能比你想象的要棘手得多。一些正则表达式解决方案可能会做得很好。但这是另一种方式,我发现。
if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules) // Standards Compliant {
csses = document.styleSheets[0].cssRules;
}
else {
csses = document.styleSheets[0].rules; // IE
}
for (i=0;i<csses.length;i++) {
if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
{
thecss[i].style.cssText="color:#000";
}
}
回答by Ryan Lanciaux
could you use jQuery on this? You could use
你能用jQuery吗?你可以用
$(".class").css("property", val); /* or use the .width property */
回答by Xingang Huang
There is a jQuery plugin called jQuery Rule, http://flesler.blogspot.com/2007/11/jqueryrule.html
有一个名为 jQuery Rule 的 jQuery 插件, http://flesler.blogspot.com/2007/11/jqueryrule.html
I tried it to dynamically set some div sizes of a board game. It works in FireFox, not in Chrome. I didn't try IE9.
我尝试用它来动态设置棋盘游戏的一些 div 大小。它适用于 FireFox,不适用于 Chrome。我没有尝试 IE9。