如何使用jquery计算高度

how to calculate height using jquery

本文关键字:高度 计算 jquery 何使用      更新时间:2023-09-26

我想计算从顶部到添加链接的点的高度

如何计算高度,例如我们使用:

w = $(window).height(); 

计算窗口的高度。

同样,我想计算锚标记 的高度
<a href="#" id="calc"></a> 

从标题到添加锚点的位置?

outerh = $('#calc').outerHeight();
innerh = $('#calc').innerHeight();

我已经尝试了上面的代码,但它返回高度的18px,因为它正在计算该锚标记的高度。

您可以使用offset().top计算。

获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。

演示:

console.log($('#calc').offset().top);
body {
  margin:0;  
}
a {
  display:inline-block;
  margin-top:100px;
}
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<a href="#" id="calc">link</a> 

锚标签距顶部的高度

height_top= $('#calc').offset().top;

锚标签从顶部到锚标签底边的高度

height_top= $('#calc').offset().top + $('#calc').outerHeight();