admin管理员组

文章数量:1323178

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.

Here is what I would like to do :

style.css:

.myClass { 
    width: $insertedFromJS 
}

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.replaceAll("$insertedFromJS", "400px");

I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.

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.

Here is what I would like to do :

style.css:

.myClass { 
    width: $insertedFromJS 
}

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.replaceAll("$insertedFromJS", "400px");

I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.

Share Improve this question edited May 2, 2012 at 20:00 Dan D. 74.7k15 gold badges110 silver badges127 bronze badges asked May 2, 2012 at 19:46 AkademiksQcAkademiksQc 6981 gold badge6 silver badges21 bronze badges 4
  • When are you running the JS? Immediately? onload? ondocumentready? – mwcz Commented May 2, 2012 at 19:49
  • 1 I'm a bit confused by the question. Are you trying to affect all elements with the class myClass or just the one you have just created? – James Montagne Commented May 2, 2012 at 19:52
  • 2 I'm with James on this one. After giving an answer to the question and then re-reading it, I'm actually confused as to what the purpose of something like this would even be. You want to "decouple" your JS and CSS by creating a CSS stylesheet that depends on Javascript to inject / replace the proper values that you are going to hard code into your Javascript code? That's pretty much the exact opposite of what the word "decouple" means. – streetlogics Commented May 2, 2012 at 20:19
  • Well ok not decouple on the object oriented way...wrong naming on my part. The goal for me is just to change the code so it is more readable. I am trying to change multiple element, since each element has a different value. I think the best is just to create a js method which purpose is only to set CSS props – AkademiksQc Commented May 2, 2012 at 20:47
Add a ment  | 

4 Answers 4

Reset to default 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-plicated 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 acplish, you might want to try defining multiple classes and just changing the className property in your js.

Setting the style, might be acplished 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";
   }
}

could you use jQuery on this? You could use

$(".class").css("property", val); /* or use the .width property */ 

There is a jQuery plugin called jQuery Rule, http://flesler.blogspot./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.

本文标签: How to dynamically set and modify CSS in JavaScriptStack Overflow