Javascript获取ID的CSS样式 [英] Javascript get CSS style for ID
本文介绍了Javascript获取ID的CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够从网页上没有使用的CSS元素获取样式。例如,这是页面:
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>
,因为您可以看到IDcustom具有值,但在文档中未使用。我想获得'custom'的所有值,而不在页面中使用它。我最近的是:
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";
}
推荐答案
创建元素并添加临时:
var result,
el = document.body.appendChild(document.createElement("div")),
styleProp = 'background-color',
style;
el.id = 'custom';
style = el.currentStyle || window.getComputedStyle(el, null);
result = el[styleProp] || "unknown";
// Remove the element
document.body.removeChild(el);
这篇关于Javascript获取ID的CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文