關於CSS中對象屬性無法在JS中用style獲取的問題


先來看一段demo

    <style>
        div{
            position:absolute;
            left: 10px;
            background: red;
            width: 100px;
            height: 100px;
        }
    </style>
    <script>
        window.onload = function () {
            var oDiv = document.getElementsByTagName("div")[0];
            alert(oDiv.style.left);  
        }
    </script>
    <body>
         <div></div>
    </body>

 FF下的顯示效果

會發現 明明在css樣式中設置了left屬性 但是獲取到的值為空

解決方案:

①將css的left屬性改到行間樣式中,即HTML內

    <body>
         <div style="left:10px"></div>
    </body>

 會發現是可以直接獲取到left屬性的值的

②可以使用currentStyle(IE Opera) getComputedStyle(FF Chrome)來獲取到我們想要的屬性值

    <script>
        window.onload = function () {
            var oDiv = document.getElementsByTagName("div")[0];
            alert(getStyle(oDiv,'left'));
        };
        function getStyle(obj,attr) {
            if(typeof getComputedStyle)
                return getComputedStyle(obj,null)[attr];
            else return obj.currentStyle[attr];
        }
    </script>

 

最后來說一下問題的原因所在:

obj.style獲取的是DOM元素CSS樣式的聲明對象簡值。obj.style可讀可寫,所以我們會發現這樣一個問題,當我們在JS代碼中沒有寫obj.style之前去讀obj.style也就是上面所發生的情況,會彈出一個空值,style只能獲取到內聯樣式的具體值,而內部和外部樣式無法獲取到具體值。所以如果要獲取CSS對象屬性值,請使用currentStyle和getComputedStyle,但是currentStyle和getComputedStyle是只讀的,所以修改CSS樣式還是要用style來修改。


免責聲明!

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



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