getBoundingClientRect().width和clientWidth都能获取设备宽度

今天看flexible.js的代码,发现获取宽度使用getBoundingClientRect而不是直接clientWidth,请问这两个方法获取宽度有什么区别吗?

document.documentElement.clientWidth

document.documentElement.getBoundingClientRect().width;


森栏
浏览 1276回答 1
1回答

烙印99

getBoundingClientRect().width获取到的其实是父级的右边距离浏览器原点(0,0)左边距离浏览器原点(0,0)的距离,即父级的宽度+2padding+2border。此时的clientWidth等于父级的宽度+2*padding,不包括边框的宽度。当不隐藏子级内容,即overflow为auto时,前者的宽度依然为这个数字,因为父级并没有改编盒模型。后者的宽度为上述得到的宽度-滚动条的宽度(17px);例子如下:&nbsp; &nbsp; <div id="divParent" style="background-color: #aaa; padding:8px; border:solid 7px #000; height:200px; width:500px; overflow:hidden;">&nbsp; &nbsp; &nbsp; &nbsp; <div id="divDisplay" style="background-color: #0f0; margin: 30px; padding: 10px;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height: 400px; width: 600px; border: solid 3px #f00;">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; var divP = document.getElementById('divParent');&nbsp; &nbsp; &nbsp; &nbsp; var divD = document.getElementById('divDisplay');&nbsp; &nbsp; &nbsp; &nbsp; var clientWidth = divP.clientWidth;&nbsp; &nbsp; &nbsp; &nbsp; var getWidth = divP.getBoundingClientRect().width;&nbsp; &nbsp; &nbsp; &nbsp; divD.innerHTML += 'clientWidth: ' + clientWidth + '<br/>';&nbsp; &nbsp; &nbsp; &nbsp; divD.innerHTML += 'getWidth: ' + getWidth + '<br/>';&nbsp; &nbsp; </script>我没看过flexible.js,只是从原生的js上给你点东西,希望对你有用!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript