modify a css rule object with javascript [duplicate]

被刻印的时光 ゝ 提交于 2019-11-26 08:32:30

问题


Possible Duplicate:
Changing a CSS rule-set from Javascript

I was wondering if there is any possibility to modify Css stylesheet declarations without going for inline styling.

Here is a quick example :

<style>
    .box {color:green;}
    .box:hover {color:blue;}
</style>

<div class=\"box\">TEXT</div>

That gives a blue written box that turns green written on hover.

If I give inline styling for the color, the hover behavior will be lost :

<div class=\"box\" style=\"color:red;\">TEXT</box>

That gives a red written box, no matter what.

So my question is, how can one access and modify the css declaration object rather than overwriting styles with inline ones.

Thanks,


回答1:


You could use the cssRules on the DOM stylesheet object corresponding to your original stylesheet to modify your rule.

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.color = 'red';

Note that IE uses rules instead of cssRules.

Here is a demonstration: http://jsfiddle.net/8Mnsf/1/




回答2:


Just define your classes, and assign/remove classes to HTML elements with javascript.

Directly assigning style to an element, has highest priority, It will override all other CSS rules.

EDIT:

you may want to use cssText property

see example here cssText property



来源:https://stackoverflow.com/questions/13528512/modify-a-css-rule-object-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!