获取样式
window.getComputedStyle(标签.想要获取的属性) //后面的.可加可不加var obj = window.getComputedStyle(box); console.log( window.getComputedStyle(box) ); console.log(obj.width);
通过点按钮使方块宽度增加:
document.querySelector("button").onclick = function(){ var timer = setInterval(function(){ // 获取宽 var obj = window.getComputedStyle(box); var w = obj.width w = parseInt(w) w += 10 if(w>=700){ clearInterval(timer) } box.style.width = w + "px" // console.log(w); },50) }
注意:不要拿颜色值判断
console.log( getComputedStyle(box)['background-color'] );有兼容性问题的
var box = document.getElementsByTagName('div') box = box[0] console.log(getComputedStyle(box).width); 在ie中使用: 标签.currentStlye console.log(box.currentStyle.height);
兼容的获取样式的函数
function getStyle(ele,attr){ if(window.getComputedStyle){ return getComputedStyle(ele)[attr] }else{ return ele.currentStyle[attr] } } var h = getStyle(box,'background-color') console.log(h); var w = getStyle(box,'width') console.log(w);