原生js和jQuery获取元素的宽高比较

截图效果和盒子模型:

在jQuery中,width()方法用于获得元素宽度;

innerWidth()方法用于获得包括内边界(padding)的元素宽度;

outerWidth()方法用于获得包括内边界(padding)和边框(border)的元素宽度;

如果outerWidth()方法的参数为true则外边界(margin)也会被包括

测试demo代码:

<!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>获取元素不同的宽度</title>
    <style>
        *{
            padding:0;
            margin:0;
        }
        body{
            background-color: pink;
        }
        #box{
            width:100px;
            height:50px;
            padding:10px;
            border:20px solid blue;
            margin:30px;
            background-color: purple;
            color:white;
        }
    </style>
</head>
<body>
    <div id="box">
        我是box的内容,我是box的内容content
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        // 原生js写法
        var box = document.getElementById('box');
        // 这种写法是错误的,没有该方法
        console.log(box.width);//undefined
        console.log(box.height);//undefined
        // 注意此方法拿到的值带有单位px
        console.log(window.getComputedStyle(box).width);//100px
        console.log(window.getComputedStyle(box).height);//50px
        console.log('offsetWidth为元素width(100)+padding(10*2)+border(20*2)' + box.offsetWidth);//160
        console.log('offsetHeight为元素height(50)+padding(10*2)+border(20*2)' + box.offsetHeight);//110
        console.log('clientWidth为元素width(100)+padding(10*2)' + box.clientWidth);//120
        console.log('clientHeight为元素height(100)+padding(10*2)' + box.clientHeight);//70
        /**
         *jQuery 写法
         */
        var jw = $('#box').width();//100
        var jh = $('#box').height();//50
        console.log(jw);
        console.log(jh);
        var jinw = $('#box').innerWidth();//120
        var jinh = $('#box').innerHeight();//70
        console.log(jinw);
        console.log(jinh);
        var joutw = $('#box').outerWidth();//160
        var jouth = $('#box').outerHeight();//110
        // 传入参数true,那么margin (top 和 bottom)也会被包含。
        var joutw = $('#box').outerWidth(true);//220
        var jouth = $('#box').outerHeight(true);//170
        console.log(joutw);
        console.log(jouth);


    </script>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值