获取元素高宽

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
 #container{
     margin: 10px;
     padding: 5px;
     width: 400px;
     border: 2px solid red;
     height: 400px;
 }
</style>
<body>
<div id="container">
</div>
<script>
    console.log("dom.style.width",document.getElementById("container").style.width);
    console.log("dom.getBoundingClientRect.width",document.getElementById("container").getBoundingClientRect().width);
    console.log("dom.offsetWidth",document.getElementById("container").offsetWidth);
    console.log("window.getComputedStyle(dom).width",window.getComputedStyle(document.getElementById("container")).width);
    console.log("dom.clientWidth",document.getElementById("container").clientWidth);
    console.log("dom.scrollWidth",document.getElementById("container").scrollWidth);
</script>
</body>
</html>

Element.clientWidth     属性表示元素的内部宽度,以像素计。该属性包括内边距,但不包括垂直滚动条(如果有)、边框和外边距

Element.getBoundingClientRect().width  有内边距和边框,无外边距

Element.style.width  只能去内联样式的宽
window.getComputedStyle(Element).width 兼容性最好,内容区的宽
dom.currentStyle.width/height;   只能在IE浏览器中获取
posted @ 2018-04-13 17:09  dengcun  阅读(87)  评论(0)    收藏  举报