简体   繁体   English

如何在JavaScript中获取错误的CSS属性值?

[英]How to get incorrect CSS property value in JavaScript?

I need to get original value of a CSS property, even if the value is incorrect. 我需要获取CSS属性的原始值,即使该值不正确。

 var el = document.getElementById('value'); var style = window.getComputedStyle(el); el.insertAdjacentText('afterbegin', style.getPropertyValue('color')); 
 #value { color: foo; } 
 <p> Property <code>color</code> value (should be <em>foo</em>): <code id="value"></code> </p> 

In the code above I used foo as a value of color property, which obviously is incorrect — there's no color with that name, nor is it accepted color format. 在上面的代码中,我使用foo作为color属性的值,这显然是不正确的-该名称没有颜色,也不接受颜色格式。 However, when I read that value in JavaScript, I get rgb(0, 0, 0) instead of foo . 但是,当我在JavaScript中读取该值时,得到的是rgb(0, 0, 0)而不是foo

I want to get original value, as it appears in stylesheet. 我想要获得原始值,因为它出现在样式表中。 How can I achieve that? 我该如何实现?

http://codepen.io/xerif/pen/NpqKBO/ http://codepen.io/xerif/pen/NpqKBO/

You have 2 separate issues 您有2个独立的问题

The first is that there are numerous different formats to set colors but browsers will only return one format for getComputedStyle .The format returned may not even be consistent cross browser. 首先是有许多不同的格式可以设置颜色,但是浏览器只会为getComputedStyle返回一种格式。返回的格式甚至可能与跨浏览器不一致。 For example one browser might return rgb and another rgba 例如,一个浏览器可能返回rgb而另一个返回rgba

The other is that when an invalid value is provided in a css rule it won't be set by the browser rendering engine and therefore is not accessible in the dom. 另一个是当在CSS规则中提供无效值时,浏览器渲染引擎将不会设置该值,因此在dom中不可访问。

What you are asking can't be done 您的要求无法完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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