前端web页面中,js应该很方便的获取div元素的高度和宽度,那么这篇文章就说一说原生JS与JQ怎么样急速的获取DIV元素的高度和宽度的方法。

jquery获取元素的宽度(jquery设置div的最小宽度方法) 第1张

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;">

 http://www.feiniaomy.com

</div>

<script>

 //获取高度

 var h = $('#mochu').height();

 //获取宽度

 var w = $('#mochu').width();

 console.log(h);

 console.log(w);

</script>

打印结果:

100

150