Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - Can jQuery change css style definition? (not individual css of each element)

I haven't seen any docs saying jQuery can change any CSS definition such as changing

td { padding: 0.2em 1.2em }

to

td { padding: 0.32em 2em }

but either have to change a whole style sheet, or change class of each element, or change css of each element.

Is changing the style definition possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is DOM access to stylesheets, but it's one of those things we tend to avoid because IE needs a load of compatibility cruft.

A better way would be typically be to trigger the change indirectly, using a simple class change on an ancestor:

td { padding: 0.2em 1.2em }
body.changed td { padding: 0.32em 2em }

Now just $('body').addClass('changed') and all the tds update.

If you really must frob the stylesheets:

var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules; // IE compatibility
rules[0].style.padding= '0.32em 2em';

This assumes that the td rule in question is the first rule in the first stylesheet. If not, you might have to go searching for it by iterating the rules looking for the right selectorText. Or just add a new rule to the end, overriding the old one:

if ('insertRule' in sheet)
    sheet.insertRule('td { padding: 0.32em 2em }', rules.length);
else // IE compatibility
    sheet.addRule('td', 'padding: 0.32em 2em', rules.length);

jQuery itself doesn't give you any special tools to access stylesheets, but it's possible there are plugins that might.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...