jQuery元素尺寸和位置信息


先貼出元素模型信息

1.css()方法獲取元素的寬高

css()方法返回的其實是getComputedStyle(node).width的值,也就是元素內容區的寬高
注意:這個是帶單位的

<script>
    $(function(){
        console.log($("div").css("width"))
        console.log($("div").css("height"))
    })
</script>

運行結果:

200px
200px

2.width() / height()

這兩個方法返回的也是元素內容區的寬高,但是不帶單位

<script>
    $(function(){
        console.log($("div").width())
        console.log($("div").height())
    })
</script>

運行結果:

200
200

3.innerWidth() innerHeight()

這兩個方法返回的元素 內容區+內邊距 的大小,即:
width+padding / height + padding

<script>
    $(function(){
        console.log($("div").innerWidth()) 
        console.log($("div").innerHeight())
    })
</script>

運行結果:

240
240

4.outerWidth() outerHeight()

這兩個方法返回的元素 內容區+內邊距+邊框 的大小,即:
width+padding+border / height + padding+border

<script>
    $(function(){
        console.log($("div").outerWidth())
        console.log($("div").outerHeight())
    })
</script>

運行結果:

260
260

5.outerWidth(true) outerHeight(true)

返回元素 內容區+內邊距+邊框+外邊距 的大小

<script>
    $(function(){
        console.log($("div").outerWidth(true))
        console.log($("div").outerHeight(true))
    })
</script>

運行結果:

646.6659999999999
300

2.元素的位置信息

1.position() 返回包含元素的位置的對象(相對於父級定位元素)

如果當前元素使用了絕對定位,則這個對象的值為它設置的top/left的值。如果當前元素沒有絕對定位,則返回它父級定位元素的距離(當前元素邊框到父級定位元素邊框的距離)的對象

<body>
    <div id="box">定位父元素
        <div class="item">非定位元素
            <div class="child">當前元素</div>
        </div>
    </div>
</body>
<script>
    $(function(){
        console.log($(".child").position())
    })
</script>

控制台打印:

{top: 87, left: 120}

2.offset( 返回當前元素相對於document位置距離的對象

返回當前元素與瀏覽器邊框的絕對距離的對象,即:如果body有滾動條,要加上被body滾動條隱藏的距離

<script>
    $(function(){
        console.log($(".child").offset()) //{top: 157, left: 283}
    })
</script>

3.獲取和設置被滾動條卷去的寬度和高度 scrollLeft()/scrollTop()

當前元素必須有滾動條,也就是說他的子元素大小要比他大,這樣滾動條才能滾動

//獲取被滾動條卷去的寬度和高度
$('.box').scrollLeft();
$('.box').scrollTop();

//設置滾動條位置(頁面回到頂部)
$(window).scrollLeft(0);
$(window).scrollTop(0);


免責聲明!

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



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