如何在纯 JavaScript 中编写 $(“#content”).height()

How to write $("#content").height() in pure JavaScript?

本文关键字:#content height JavaScript      更新时间:2023-09-26

在我的新项目中,我必须在没有jQuery的情况下做一些内容。如何在纯JavaScript中编写下面的jQuery代码?

$("#content").height()

当然,$("#content")在 JS var content = document.getElementById('content'); 中,但.height()对我来说是一个大问题。请帮忙

等于 $('#content').height() 是:

document.getElementById('content').clientHeight;

或等于$('#content').css('height')

document.getElementById('content').style.height;
var content = document.getElementById("content");
content.clientHeight;

如评论中所述,adeneo的解决方案不正确,因为它会考虑不必要的填充到高度中。

要获得与jQuery的.height()提供的相同的维度,这是您想要使用的代码。

const s = window.getComputedStyle(el, null),
height = el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));

这是一个函数,它将帮助计算jQuery的所有高度获取器函数。如果你想计算宽度,你只需要改变代码中的一些明显的属性。

function getHeight(el, type) {
    if (type === 'inner')  // .innerWidth()
        return el.clientHeight;
    else if (type === 'outer')  // .outerWidth()
        return el.offsetHeight;
    const s = window.getComputedStyle(el, null);
    if (type === 'height' || !type)  // .height()
        return el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));
    else if (type === 'full')  // .outerWidth( includeMargins = true )
        return el.offsetHeight + parseInt(s.getPropertyValue('margin-top')) + parseInt(s.getPropertyValue('margin-bottom'));
    return null;
}