获取非行内样式操作
1、 window.getComputedStyle(dom元素).属性
注意:在IE中,只有在ie9及以上才能获取
写法: var style = window.getComputedStyle(dom元素).height;
2、dom元素.currentStyle.属性
注意:只有在ie8及以下才能获取样式,在其他浏览器会报错
写法:var style = dom元素.currentStyle.height
// 获取非行内的样式
// getComputedStyle(dom元素).属性 只有在ie9及以上才能获取
// var style = window.getComputedStyle(box).height;
// 只有在ie8及以下才能获取样式,在其他浏览器会报错
// var style = box.currentStyle.height
说明
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
height: 500px;
}
</style>
</head>
<body>
<div style="width:200px"></div>
<ul id="list"></ul>
<script>
var box = document.querySelector('div');
var styW = box.style.width;
var styH = box.style.height;
// box.style 只能获取 行内样式
// console.log(styW);
// console.log(styH);
// 获取非行内的样式
// getComputedStyle(dom元素).属性 只有在ie9及以上才能获取
// var style = window.getComputedStyle(box).height;
// 只有在ie8及以下才能获取样式,在其他浏览器会报错
// var style = box.currentStyle.height
// 获取样式的兼容写法
var style;
//先判断 if条件在ie8浏览器中 没有 window.getComputedStyle(box) 会报错
// if (window.getComputedStyle(box)) {
// style = window.getComputedStyle(box).height;
// } else {
// console.log(1);
// style = box.currentStyle.height;
// }
// console.log(box.currentStyle);
// box.currentStyle 在高版本的浏览 不会报错,返回一个undefined
// 写兼容获取样式的时候 直接使用 box.currentStyle
// if (box.currentStyle) {
// style = box.currentStyle.height;
// } else {
// style = window.getComputedStyle(box).height;
// }
// console.log(style);
// 封装一个函数 来获取非行内样式
function getStyle(ele, attr) {
var style;
if (ele.currentStyle) {
// ele.currentStyle 包含 所有css样式的对象
// obj.attr 获取 obj的 attr的属性
style = ele.currentStyle[attr];
} else {
style = window.getComputedStyle(ele)[attr];
}
console.log(style);
}
getStyle(box, 'width')
</script>
</body>
</html>
封装一个函数 来获取非行内样式
// 封装一个函数 来获取非行内样式
function getStyle(ele, attr) {
var style;
if (ele.currentStyle) {
// ele.currentStyle 包含 所有css样式的对象
// obj.attr 获取 obj的 attr的属性
style = ele.currentStyle[attr];
} else {
style = window.getComputedStyle(ele)[attr];
}
// 把获取的样式返回
return style
}
测试封装函数(不同浏览器下)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background: red;
color: blue;
font-size: 20px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box');
var res = getStyle(box, 'background-color');
console.log(res); //rgb(255, 0, 0)
function getStyle(ele, attr) {
var style;
if (ele.currentStyle) {
// ele.currentStyle 包含 所有css样式的对象
// obj.attr 获取 obj的 attr的属性
style = ele.currentStyle[attr];
} else {
style = window.getComputedStyle(ele)[attr];
}
// 把获取的样式返回
return style
}
</script>
</body>
</html>