body代码:<div id="box"></div><button id="btn1">修改内联样式</button><button id="btn2">读取内联样式</button>---->js代码:var box = document.getElementById('box')var btn1 = document.getElementById('btn1')btn1.onclick = function(){box.style.width = '300px';box.style.height = '300px';box.style.backgroundColor = 'red'}var btn2 = document.getElementById('btn2')btn2.onclick = function(){alert(getStyle(box,'width'))}// 定义一个函数,用来获取指定元素的样式// 参数一:obj要获取样式的元素,name要获取的样式名function getStyle(obj,name){if(window.getComputedStyle){// 一般浏览器,具有getComputedStyle()方法return getComputedStyle(obj,null)[name]}else{// IE8及以下浏览器不具有getComputedStyle()方法,具有currentStyle()return obj.currentStyle[name]}// 第二种方法// return window.getComputedStyle?getComputedStyle(obj,null)[name]:obj.currentStyle[name]}
