情况分为两种:第一种 行内样式 第二种 其他样式
一、行内样式获取比较简单,一般通过element.style.attr即可获取样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var dom = document.getElementById('demo')
console.log(dom.style.width) // 300px
</script>
</head>
<body>
<div id="demo" style="width: 300px;height: 500px;color: red;"></div>
</body>
</html>
二、其他样式。这里以class样式为例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.demo {
width: 300px;
height: 500px;
color: red;
}
</style>
<script>
var dom = document.getElementsByClassName('demo')
let style = null
// IE浏览器下写法
style = dom.currentStyle['width']
// 非IE浏览器(如谷歌、oprea)下写法
style = getComputedStyle(dom, null)['width']
// 通过三元运算实现 兼容IE和非IE浏览器写法
style = dom.currentStyle ? dom.currentStyle['width'] : getComputedStyle(dom, null)['width']
console.log(style) // 300px
</script>
</head>
<body>
<div class="demo"></div>
</body>
</html>
注意: 非行内样式获取法,只能获取不能设置。