Javascript 获取 ID 的 CSS 样式
我希望能够从网页上未使用的 CSS 元素获取样式。例如,这是页面:
<html>
<head>
<style type="text/css">
#custom{
background-color: #000;
}
</style>
</head>
<body>
<p>Hello world</p>
</body>
</html>
正如您所看到的,ID“custom”有一个值,但在文档中未使用。我想获取“自定义”的所有值,而不在页面中使用它。我最接近的是:
el = document.getElementById('custom');
var result;
var styleProp = 'background-color';
if(el.currentStyle){
result = el.currentStyle[styleProp];
}else if (window.getComputedStyle){
result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
}else{
result = "unknown";
}
I would like to be able to get the style from a CSS element which is not used on the webpage. For example, this is the page:
<html>
<head>
<style type="text/css">
#custom{
background-color: #000;
}
</style>
</head>
<body>
<p>Hello world</p>
</body>
</html>
as you can see the ID 'custom' has a value but is not used within the document. I would like to get all the values for 'custom' without using it in the page. The closest I have come is:
el = document.getElementById('custom');
var result;
var styleProp = 'background-color';
if(el.currentStyle){
result = el.currentStyle[styleProp];
}else if (window.getComputedStyle){
result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
}else{
result = "unknown";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用给定 ID 创建一个新元素并将其附加到文档中。然后只需读取该值并删除该元素即可。
例子:
Create a new element with given ID and append it to the document. Then just read the value and remove the element.
Example:
我认为答案不是一个很好的答案,因为它需要向 DOM 添加元素,这可能会破坏您正在尝试执行的操作或产生视觉故障。
使用 document.styleSheets 我认为你可以获得一个侵入性较小的解决方案。 (请参阅此处)
尝试如下操作:
这应该为您提供一个包含所有内容的对象样式作为键。请记住,如果在样式表中重新声明样式,您可能需要更复杂的算法。
I don't think the answer was a very good one as it requires adding elements to the DOM which may disrupt what you are trying to do or create visual glitches.
Using document.styleSheets I think you can get a less invasive solution. (see here)
try something like:
This should give you an object which will contain all of the styles as the keys. keep in mind you may need a little more complex algorithm if the style is redeclared within the stylesheets.