问题
Is there a way to override how javascript converts complex CSS color names to rgb values when applying them to DOM elements in the document.getElementById(xxx).style
object.
For example: setting document.getElementById("colorMe").style.background = "lightblue"
will set the "DOMElement".style
object with a background = "rgb(...)"
.
However, setting document.getElementById("colorMe").style.background
= "blue" will set the "DOMElement".style
object with a background = "blue"
.
I WANT the second version for all cases of color names, not just simple color names.
I would like to bypass how javascript is converting that color into an RGB value for complex color names. Is this possible?
EDIT: I Am aware there are ways to convert back and forth, I am just trying to bypass how javascript seems to be converting them "for me"... I'd like it to stay as "lightblue", and the browser seems to handle lightblue as a background color just fine.
回答1:
You could use setAttribute
:
element.setAttribute('style', 'background-color: lightblue');
To preserve the existing inline style:
var box = document.getElementById("box"),
old_style = box.getAttribute('style');
box.setAttribute('style', old_style + ' background-color: lightblue;');
DEMO
Notice that the inline background-color
is 'lightblue' and not 'rgb(173, 216, 230).'
来源:https://stackoverflow.com/questions/14641065/javascript-style-object-converts-complex-color-names-into-rgb