如何用纯JavaScript编写$(“content”).height()?

如何用纯JavaScript编写$(“content”).height()?,javascript,jquery,Javascript,Jquery,在我的新项目中,我必须在没有jQuery的情况下完成一些内容。如何用纯JavaScript编写下面的jQuery代码 $("#content").height() 可以肯定的是,$(“#content”)在JSvar content=document.getElementById(“content”)中,但是.height()对我来说是个大问题。请帮助等同于$(“#内容”)。高度()将是: document.getElementById('content').clientHeight; 或等

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

$("#content").height()
可以肯定的是,
$(“#content”)
在JS
var content=document.getElementById(“content”)中
,但是
.height()
对我来说是个大问题。请帮助等同于
$(“#内容”)。高度()
将是:

document.getElementById('content').clientHeight;
或等于
$('#content').css('height')


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

要获得jQuery的
.height()
提供的相同维度,您需要使用以下代码

const s = window.getComputedStyle(el, null),
height = el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));
下面是一个函数,它将帮助计算jQuery的所有height getter函数。如果要计算宽度,只需更改代码中的一些明显属性

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

正如其他信息一样:答案是
clientHeight
。但有一天,你可能会在视线之外偶然发现
,这可能会让你感到困惑。下面是对每一个问题的解释:好的,谢谢你,这是我最后一次将代码重写到纯JSF中。这是不正确的,因为clientHeight将在计算中包含填充。因此,内容高度为10px,顶部和底部填充5px的div的高度为20px,但jquery的height()将返回10px@StevenBrookes-早在2013年,我相信jQuery实际上在内部使用了
clientHeight
,所以答案是正确的。现在,jQuery使用了几种技巧来获得没有填充的高度,包括样式和比较等。如果确实遇到了问题,并且需要在纯javascript中获得没有填充的高度,则必须实际获得填充,然后从
clientHeight
中减去顶部和底部填充,因为实际上没有直接返回它的函数。还要注意,
elem.style.height
与jQuery的
css()
函数并不完全相同,因为jQuery有大约一百行代码,使用cssHooks和cssProps获取当前样式并返回元素的维度,即使没有专门设置样式,等等,但在大多数情况下,
elem.style
将返回相同的值。
const s = window.getComputedStyle(el, null),
height = el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));
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;
}