问题
I'm altering a class definition in a stylesheet by using the following code:
/*
* At this point it is:
* "position: absolute; height: 20px; background-image: none; background-position: initial initial; background-repeat: initial initial;"
* But I actually set "background: none;" in my css file
*/
var cssText = document.styleSheets[ 0 ][ "cssRules" ][ 3 ].style.cssText;
//Just replace the height
document.styleSheets[ 0 ][ "cssRules" ][ 3 ].style.cssText = cssText.replace( "height: 20px", "height: 14px" );
/*
* Now when I print it out, it's:
* "position: absolute; height: 20px;"
*/
console.log( document.styleSheets[ 0 ][ "cssRules" ][ 3 ].style.cssText );
If I re-append "background: none;" then it puts back in the "background-image: none; background-position: initial initial; background-repeat: initial initial;" stuff. (Oddly, if I append "background-image: none; background-position: initial initial; background-repeat: initial initial;", then it just appears without any background info!)
Any idea why this happens?
Edit: The reason I'm using cssText instead of direct access to the styles is that on a number of them I need to set "!important" and there's no way other than cssText to do this.
来源:https://stackoverflow.com/questions/17353184/why-does-altering-the-height-in-csstext-remove-the-background-none