Changing Css Rules Using Javascript Or Jquery
Solution 1:
Ok, if:
Personal Preference
Then use user styles CSS. According to priority, user styles takes precedence above all other styles. Next comes inline-styles, then
!important
styles, then specificity, then default browser styles. If it's just for personal preference, pack-up a custom CSS with you and a browser that supports it.You are the developer
Then don't do this in JavaScript or user scripts. Go down to the problem and change those styles! You are just making the browser work more by actually making it parse stuff you don't want. Since you have access to the code, change the styles instead.
However, since your site could be a public site, style it like genericly for everyone. It's not only you that's viewing the site.
Not the developer:
The best way I can think of (and already did this before*) is to remove external stylesheets from the page and replace them with modded versions of your own liking. That is taking a copy of the original CSS file, change what needs to be changed, and then load it via JS by creating a
<link>
to that external file, or load the contents via AJAX and put them in a<style>
. However, this approach is riddled with obstacles.<link>
does not have anonload
event so you won't know the external CSS was loaded (there are crafty workarounds though) and AJAXing CSS contents imply that your CSS is in the same domain or the browser and server supports CORS.Another way you can do it is to have JS peek into loaded stylesheets and modify their contents. This is a more JS intensive work since JS looks for your definition to change in a pile of CSS declarations. This is a safer bet, however, I believe not all browsers can traverse CSS styles or at least do it differently across browsers. Also, if you got a large stylesheet, you'd be parsing it every time.
As you said,
.css()
would be recursive. True, because it applies inline styles to each affected element. This is good in a sense that inline styles are higher up in the priority so whatever is placed using.css()
, you are almost sure that they will take effect. However, it's more work intensive since it involves the DOM now.
* The library I created does not remove existing styles, it just loads and unloads predefined styles declared using it's API
Solution 2:
Have a look at:
- Quirksmode: Change CSS
- Totally Pwn CSS with Javascript
- Is the only way to change a style to do it per-element in JavaScript? (possible duplicate)
I'm afraid there is no library for that, I really would like to see one...
Post a Comment for "Changing Css Rules Using Javascript Or Jquery"