欢迎光临
我们一直在努力

js获取div元素高度与宽度的方法

js获取div元素高度与宽度的方法

js获取div元素的高度与宽度要用的 clientHeight 与 clientWidth方法

clientHeight:返回元素的可视高度

clientWidth:返回元素的可视宽度

示例代码:

<div id="mochu" style="height: 200px;width:150px;color:#fff;background-color: blueviolet;">
    
</div>
<script>
    //获取高度
    var h = document.getElementById('mochu').clientHeight;
    //获取宽度
    var w = document.getElementById('mochu').clientWidth;
    console.log(h);
    console.log(w);
</script>

打印结果:

200
150

jquery获取div元素高度与宽度的方法

相对于原生的 javascript 来说,使用 jquery 来获取 div 元素的高度与宽度要简单的多。

jq获取div元素宽度的方法

$(selector).width()

jq获取div元素高度的方法

$(selector).height()

示例代码:

<div id="mochu" style="height: 100px;width:150px;">
</div>
<script>
    //获取高度
    var h = $('#mochu').height();
    //获取宽度
    var w = $('#mochu').width();
    console.log(h);
    console.log(w);
</script>

打印结果:

100
150
赞(0)
未经允许不得转载:学习技术 » js获取div元素高度与宽度的方法