jq 獲取元素的尺寸

jq 獲取元素的尺寸

  • 獲取元素尺寸
  • jquery-3.4.1 是可以獲取隱藏元素的寬高的,下面的方法都可以獲取隱藏元素的寬高
方法作用
width()獲取元素的內容寬度
height()獲取元素的內容高度
innerWidth()獲取元素(內容+padding)寬度
innerHeight()獲取元素(內容+padding)高度
outerWidth()獲取元素(內容+padding+border)寬度
outerHeight()獲取元素(內容+padding+border)高度
outerWidth(true)獲取元素(內容+padding+border+margin)寬度
outerHeight(true)獲取元素(內容+padding+border+margin)高度
  • 其他常用尺寸
寫法作用
$(window).width()獲取瀏覽器可視區寬度
$(window).height()獲取瀏覽器可視區高度
$(document).width()獲取頁面寬度
$(document).height()獲取頁面高度
$('body').width()獲取頁面寬度,body默認有8px的margin
$('body').height()獲取頁面高度,body默認有8px的margin
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background: Red;
            padding: 10px;
            border: 5px black solid;
            margin: 3px;
            display: none;
        }
    </style>
    <script src="./jquery-3.4.1.js"></script>
</head>

<body style="height: 3000px;">
    <div></div>
    <script>
        //得到元素的內容寬度、高度 width() height()
        console.log($('div').width()); //100 
        console.log($('div').height()); //100 

        //得到元素的內容+padding innerWidth() innerHeight()
        console.log($('div').innerWidth()); //120
        console.log($('div').innerHeight()); //120 

        //得到元素的內容+padding+border outerWidth() outerHeight()
        console.log($('div').outerWidth());  //130
        console.log($('div').outerHeight()); //130

        //得到元素的內容+padding+border+margin outerWidth(true) outerHeight(true)
        console.log($('div').outerWidth(true));  //136
        console.log($('div').outerHeight(true)); //136

        //設置元素寬高
        $('div').width(300);
        $('div').height(300);
        console.log($('div').width()) //300
        $('div').innerWidth(300);
        console.log($('div').width());//280  內容=300-padding
        $('div').outerWidth(300)
        console.log($('div').width());//270 內容=300-padding-border
        $('div').outerWidth(300, true)
        console.log($('div').width()); //264 內容=300-padding-border-margin

        //原生js 是獲取不到隱藏元素的寬高的
        console.log($('div').get(0).offsetWidth) //0 get將jq獲取的元素轉成js原生的元素 get參數不寫的話,輸出undefind
        //因爲$('div')返回的對象是個數組,不管有沒有值,返回的都是數組,所以需要加0

        //jq是可以獲取隱藏元素的寬高的
        console.log($('div').width())  //264

        //其他尺寸
        //瀏覽器可視區的寬高 $(window).width() $(window).height
        console.log($(window).width())
        console.log($(window).height())

        //頁面寬高 $(document).width() $(document).height() $('body').width() $('body').height()
        console.log($(document).width()); //877
        console.log($('body').width()); //861 //左右兩邊默認 margin 8px
    </script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章