1. 程式人生 > 其它 >js基礎---正常瀏覽器與IE獲取元素的樣式 getComputedStyle/元素.currentStyle

js基礎---正常瀏覽器與IE獲取元素的樣式 getComputedStyle/元素.currentStyle

-正常瀏覽器 -使用getComputedStyle() -這個方法是window物件的方法,可以返回一個物件,這個物件中儲存著當前元素生效樣式 -引數: 1.要獲取樣式的元素 2.可以傳遞一個偽元素,一般傳null -例子: 獲取元素的寬度 getComputedStyle(box,null)["width"]; -通過該方法讀取到樣式都是隻讀的不能修改
-IE8 -使用currentStyle -語法: 元素.currentStyle.樣式名 -例子: box.currentStyle["width"] -通過這個屬性讀取到的樣式是隻讀的不能修改
            window.onload = function
(){ var bx1 = document.getElementById("box1"); document.querySelector(".btn1").onclick = function(){ bx1.style.height = "400px"; bx1.style.width = "400px"; bx1.style.backgroundColor = "red"; } document.querySelector(
".btn2").onclick = function(){ if(window.getComputedStyle){ // 正常瀏覽器 alert(getComputedStyle(bx1,null).backgroundColor); }else{ //IE8 alert(bx1.currentStyle.backgroundColor); } } }