<div></div>
<button id="btn">按钮</button>
<script type="text/javascript">
var div = document.getElementsByTagName("div")[0]
var btn = document.getElementById("btn")
btn.onclick = function(){
// console.log(div.currentStyle.width)
// div.style.width="300px"
// alert(div.style.backgroundColor)
// 获取当前元素样式
// 这个方法是window对象的方法,可以返回一个对象,这个对象中保存着当前元素生效样式
/*
参数:
1.要获取样式的元素
2.可以传递一个伪元素,一般传null
*/
var obj = window.getComputedStyle(div,null)
console.log(obj.width)
console.log(obj.backgroundColor)
// 通过该方法读取到样式都是只读的不能修改
// obj.width = "500px"
var g = getStyle(div,"width")
console.log(g)
}
/*
定义一个函数:获取指定的元素信息
参数1: 指定获取元素信息的元素
参数2: 获取元素的样式名
*/
function getStyle(element,name){
if(window.getComputedStyle){
return window.getComputedStyle(element,null)[name]
}else{
return element.currentStyle.name
}
}
</script>
读取元素的样式
最新推荐文章于 2024-07-30 17:09:59 发布