在我的新项目中,我必须在没有jQuery的情况下做一些内容。如何在纯JavaScript中编写下面的jQuery代码?
$("#content").height()
当然可以,$("#content")
在JS var content = document.getElementById('content');
中,但.height()
对我来说是个大问题。请帮忙
答案 0 :(得分:10)
等同于$('#content').height()
将是:
document.getElementById('content').clientHeight;
或等同于$('#content').css('height')
document.getElementById('content').style.height;
答案 1 :(得分:0)
var content = document.getElementById("content");
content.clientHeight;
答案 2 :(得分:0)
如评论中所述,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;
}