Javascript style object converts complex color names into rgb

大城市里の小女人 提交于 2019-12-11 08:36:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!