我通过三种方式插入CSS
- 内联样式(p1)
- 内部样式表(p2)
- 外部样式表(p3)
我想通过 Javascript && Jquery 获取每个 css 的值。请告诉我如何做。
我无法以与 p1 相同的方式获取 p2 、 p3 的值。怎么了?
非常感谢!
window.onload = abc();
function abc(){
var p1 = document.getElementById('p1').style.height;
document.getElementById('p1').innerHTML = p1;
var p2 = document.getElementById('p2').style.width;
document.getElementById('p2').innerHTML = p2;
var p3 = document.getElementById('p3').style.height;
document.getElementById('p3').innerHTML = p3;
}
#p3{
width: 200px;
height: 200px ;
background-color: aqua ;
}
<!DOCTYPE html>
<head>
<title>CSS Element output</title>
</head>
<body>
<H1>CSS output element property</H1>
<div id="p1" style="height:50px;width:100px;">check p1</div>
<div id="p2">check p2</div>
<style>
#p2{
height:50px;
width:400px;
background-color: bisque
}
</style>
<div id="p3">check p3</div>
</body>
**
强文字
**
最佳答案
您可以使用 window.getCompulatedStyle();
和 getPropertyValue();
获取样式属性的值
请参阅下面的示例代码来获取元素 p2 的高度值:
var element = document.getElementById('p2'),
style = window.getComputedStyle(element),
res = style.getPropertyValue('height');
alert(res);
关于javascript - 通过JS和Jquery获取CSS元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422463/