简体   繁体   中英

Modifying of css by document.styleSheets

I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

From MDN docs (about DocumentOrShadowRoot.styleSheets ):

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Expect behavior to change in the future.

I would therefore advise against using the method.

I can't, however, explain in any more detail why you're seeing the problem you describe, as most browsers are supposed to support this feature in the linked compatibility table.


Now to answer your next question:

how can I modify CSS different way?

I would always get an element through the DOM first and then apply styles to an element directly. For example:

var myEl = document.getElementById("myId");

Then you can do:

myEl.style.fontSize = "1rem";


If you don't want to target the element by its id attribute, you can use several other methods:

  1. getElementsByClassName() – takes a string value of a class name, eg. "myClass"
  2. getElementsByTagName() – takes a string value of a tag name, eg. "body" , "div"
  3. querySelector() – takes a string value of a CSS selector eg. "div.myClass p"

However, these don't return a single element like the id selector. For example, to get the first element of a particular class:

var myEl = document.getElementsByClassName("myClass")[0];

And the fourth would be:

var myEl = document.getElementsByClassName("myClass")[3];

Modifying styleSheets directly can be tricky.

I prefer to append a new style element to the document and place the modified CSS in there. Since it is the last style element in the document, it will override any earlier CSS rule that has a matching selector.

For example, this will set the font size of the body to 1rem:

let style = document.createElement('style');
style.innerHTML = 'body { font-size: 1rem; }';
document.head.appendChild(style);

When I last dealt with this manipulating the CSSOM was not supported very well by many browsers (and I think that didn't change yet).

If you want to apply styles to single Element do it on the Element directly.

If you want to generate css rules at runtime you could also consider dropping a style tag into your document:

var style = document.createElement('style');

// set style properties
// append the style tag to the head or somewhere in the body

head.appendChild(style);

You will have more control using css variables, below you can find a small demo that illustrates my point

 let root = document.documentElement; document.querySelector('button').addEventListener('click', () => { let currentVal = Number(getComputedStyle(root).getPropertyValue('--defaultFontSize').replace('px', '')); root.style.setProperty('--defaultFontSize', `${currentVal + 5}px`); });
 :root { --defaultFontSize: 20px; }.text { font-size: var(--defaultFontSize); }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <p class="text">Some text</p> <button>Increse font size</button> </body> </html>

If you have the classname or id of whatever you want to modify, you can use the jquery css() method.

eg: $("#whateverID").css('font-size', '1rem');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM