开发者

Applying CSS in JavaScript indirectly

开发者 https://www.devze.com 2023-02-12 05:04 出处:网络
When you write real CSS you could do .blue { color: blue; } and if you added the class \"blue\" to an element after loading, it would turn blue.

When you write real CSS you could do

.blue { color: blue; }

and if you added the class "blue" to an element after loading, it would turn blue.

In JavaScript you wo开发者_JAVA技巧uld have to do something like

var blue = document.getElementsByClassName('blue');
for (var i = 0; i < blue.length; i++)
     blue[i].style.setProperty('color', 'blue');

The problem with the JavaScript version is if you did

document.getElementById('someId').className += " blue";

it would have the class blue, but it would not turn blue. Is there any way (preferably simple) to add the style to the selector rather then directly to the elements with that selector?


The most common way is defining .blue { color:blue; } in the CSS beforehand, then adding the class to the element via JS. That way styles are in the CSS and only class names are in the JS, making it more flexible instead of hardcoding dozens of css keys/values in the JS.


See this question. You can add a <style> element via JavaScript.


The HTML

<div id="test">This will turn blue</div>
<button onclick="addClass()" >add Class </button>

The Javascript

function addClass(){
    document.getElementById('test').className += 'blue';
}

The CSS

.blue{
     color:blue;
}

This works in FF IE7 and Chrome. Perhaps there is something else going on in your code which is stopping this from working.

0

精彩评论

暂无评论...
验证码 换一张
取 消