3

我有一些 JavaScript 代码可以创建一些div元素并设置它们的 CSS 属性。因为我想将 CSS 逻辑从我的 JavaScript 代码中分离出来,并且因为 CSS 在它自己的.css文件中更容易阅读,所以我想设置className我的元素的 CSS,然后动态地将一些值注入到定义的 CSS 属性中。

这是我想做的:

style.css

.myClass { 
    width: $insertedFromJS 
}

script.js

var myElement = document.createElement("div");
myElement.className = "myClass";

我想做这样的事情,但那时myElement.style.width是空的

myElement.style.width.replaceAll("$insertedFromJS", "400px");

我认为我的问题是在调用 之后myElement.className = "myClass",尚未应用 CSS。

4

4 回答 4

2

设置样式,可以通过定义内页样式声明来完成。

这就是我的意思

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";
   }
}
于 2012-05-02T20:02:38.013 回答
2

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 then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...

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 whole lot you can do about that. You're trying to set css dynamically, after all.

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.

于 2012-05-02T20:10:57.123 回答
0

你能在这个上使用jQuery吗?你可以使用

$(".class").css("property", val); /* or use the .width property */ 
于 2012-05-02T19:50:06.030 回答
-2

There is a jQuery plugin called jQuery Rule, 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.

于 2013-10-21T17:26:57.213 回答