// 获取元素的高度
// 方法一:使用 offsetHeight
// offsetHeight 返回元素的布局高度,包括 padding、border 和 height,但不包括 margin。
const element = document.getElementById('myElement');
const height = element.offsetHeight;
console.log(height); // 输出元素的高度
// 方法二:使用 getBoundingClientRect()
// getBoundingClientRect() 返回一个 DOMRect 对象,提供了元素的大小及其相对于视口的位置。
const rect = element.getBoundingClientRect();
const clientHeight = rect.height;
console.log(clientHeight); // 输出元素的高度
// 方法三:使用 style 属性(仅适用于行内样式)
// 注意:这种方法只适用于直接在 HTML 中定义的行内样式,并且返回的是字符串形式的高度值。
const inlineHeight = window.getComputedStyle(element).height;
console.log(inlineHeight); // 输出元素的高度,带单位(如 "100px")
// 方法四:使用 scrollHeight
// scrollHeight 返回元素的内容高度,包括那些由于溢出而不可见的部分。
const scrollHeight = element.scrollHeight;
console.log(scrollHeight); // 输出元素的滚动高度
offsetHeight
包含了 padding 和 border,但不包含 margin。getBoundingClientRect()
提供了更详细的信息,包括元素相对于视口的位置和尺寸。window.getComputedStyle()
可以获取元素的所有计算样式,包括高度。scrollHeight
用于获取元素的完整内容高度,即使部分内容超出了可见区域。上一篇:js 显示时间
下一篇:js checkbox选中
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站