Window.getComputedStyle()
Window.getComputedStyle()方法返回一个对象,该对象包含元素的所有 CSS 属性的值。
获取元素属性
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
let elem = document.getElementById("elem-container");
let theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
获取 CSS 变量
<script>
// 获取根元素
var r = document.querySelector(':root');
// 创建获取变量值的函数
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --blue variable
alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}
// 创建设置变量值的函数
function myFunction_set() {
// Set the value of variable --blue to another value (in this case "lightblue")
r.style.setProperty('--blue', 'lightblue');
}
</script>
参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
https://www.w3school.com.cn/css/css3_variables_javascript.asp
https://wow.techbrood.com/fiddle/32675
修改时间 2022-02-19
声明:本站所有文章和图片,如无特殊说明,均为原创发布,转载请注明出处。