1. 程式人生 > >JS——獲取屬性

JS——獲取屬性

func att pre ack 屬性 spa function .get urn

window.getComputedStyle(div, null)

<script>
    var div = document.getElementsByTagName("div")[0];
    console.log(typeof  window.getComputedStyle(div, null));//object
    console.log(window.getComputedStyle(div, null).width);//400px
    console.log(window.getComputedStyle(div, null)["width"]);//400px
    console.log(window.getComputedStyle(div, 
null)["background-color"]);//rgb(255, 192, 203) console.log(window.getComputedStyle(div, null).backgroundColor);//rgb(255, 192, 203) </script>

div.currentStyle(IE678)

<script>
    var div = document.getElementsByTagName("div")[0];
    console.log(div.currentStyle["width"]);
    console.log(div.currentStyle.width);
</script>

兼容寫法

<script>
    var div = document.getElementsByTagName("div")[0];
    console.log(getStyle(div, "width"));
    console.log(getStyle(div, "backgroundColor"));

    function getStyle(ele, attr) {
        if (window.getComputedStyle) {
            return window.getComputedStyle(ele, 
null)[attr]; } return ele.currentStyle[attr]; } </script>

註意事項:普通獲取屬性方式div.style.width或者div.style["width"]無法獲取內嵌和外鏈式,只能獲取行內式

JS——獲取屬性