js中style,currentStyle和getComputedStyle的區別以及獲取css操作方法


在js中,之前我們獲取屬性大多用的都是ele.style.border這種形式的方法,但是這種方法是有局限性的,該方法只能獲取到行內樣式,獲取不了外部的樣式.所以呢下面我就教大家獲取外部樣式的方法,因為獲取外部的樣式存在兼容性的問題,所以后面我還會教大家解決兼容性的方法.

style:各大瀏覽器都兼容,能設置樣式和獲取樣式,但是獲取不了外部樣式,如果寫了行內沒有的樣式,返回的是空值

寫法:ele.style.attr(這樣為獲取),ele.style.attr="值";

 

currentStyle屬性和getComputedStyle屬性不能設置屬性,只能獲取

currentStyle:該屬性只兼容IE,不兼容火狐和谷歌

 寫法:ele.currentStyle["attr"]或者ele.currentStyle.attr;

getComputedStyle:該屬性是兼容火狐谷歌,不兼容IE

寫法:window.getComputedStyle(ele,null)[attr]獲取是window.getComputedStyle(ele,null).attr

下面我就貼上我的代碼:

var div=document.getElementsByTagName("div")[0];
        if(div.currentStyle){
            //IE上兼容
            console.log(div.currentStyle["width"]);
        }
        else{
            //火狐谷歌上兼容
            console.log(window.getComputedStyle(div,null)["width"]);
        }

下面呢,我寫了一個兼容性的方法,大家可以參考參考:

        var div=document.getElementsByTagName("div")[0];

        console.log(getStyle(div,"background-color"));
        function getStyle(ele,attr){
            if(window.getComputedStyle){
                return window.getComputedStyle(ele,null)[attr];
            }
            return ele.currentStyle[attr];
        }

說明:在IE中獲取到的顏色是16進制的,在火狐谷歌中獲取的顏色是rgb模式的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM