一、设置和获取行内的样式
<div id="box"></div>
<script>
//设给元素置样式 (注意这设置的是行内样式)
var obox = document.getElementById('box')
obox.style.width = '200px';
obox.style.height = '200px';
obox.style.background = 'red'
// 获取 (带单位,且只能获取行内的样式)
console.log(obox.style.width) //200px
console.log(obox.style.height) //200px
console.log(box.style.background) //red
</script>
这种方式只能获取行内的样式
二、style内的样式的获取
用getComputedStyle(元素).width 这种方法既可以获取style内的也可以获取行内的
<div id="box" style="width: 100px"></div>
<script>
var obox = document.getElementById('box')
// getComputedStyle(元素).样式名 这个方法得到计算以后的元素的样式 行内和style里的都能得到
console.log(getComputedStyle(obox).width) //200px带单位
console.log(getComputedStyle(obox).height) //200px带单位
console.log(getComputedStyle(obox).background) //rgb(255, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box
console.log(getComputedStyle(obox).backgroundColor) //rgb(255, 0, 0)
</script>
//但是有兼容性问题 IE8及以下没有 用
元素.currentStyle.样式名
封装方法
```csharp
<div id="box" style="width: 100px"></div>
<script>
var obox = document.getElementById('box')
// 这个方法用于获取元素的样式
// 传几个参数 1.目标 2.样式
//兼容IE8及以下
function getStyle(obj, attr) {
//判断是否有这个函数,没有会返回undefined
if (typeof(getComputedStyle) == 'function') {
// IE9及以上
return getComputedStyle(obj)[attr]
//为什么不是点呢 因为.就把attr变成了字符串 所以用[]形式
} else {
// IE8及以下
return obj.currentStyle[attr]
}
}
console.log(getStyle(obox, 'width'))