gpt4 book ai didi

javascript - 查找元素高度,包括边距

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:32 24 4
gpt4 key购买 nike

我正在制作一个简单有趣的绘图应用程序,其中的结构如下:

  • 标题
  • Canvas
  • 页脚

我试图让 Canvas 成为窗口的完整高度,减去页眉高度和页脚高度。

我试过很多东西,比如:

canvas.height = window.height - (document.getElementById("header").offsetHeight + document.getElementById("footer").offsetHeight);

我什至尝试过:

function getHeight(id) {
id = document.getElementById(id);
return id.offsetHeight + id.style.marginTop + id.style.marginBottom;
}

canvas.height = window.height - (getHeight("header") + getHeight("footer"))

但是没有用。在控制台中 id.style.marginTop 只是返回了一个空字符串,虽然它的 marginTop 是在 css 中设置的...只是没有专门设置为 marginTop,它被设置为 margin: 8px 0 8px 0;

有什么方法可以在不使用 jQuery 的情况下获取元素的渲染高度,包括边距?

我假设我们必须使用 id.style.marginmargin: 8px 0 8px 0; 分成单独的变量...但是我只是不确定如何将其分开。

最佳答案

function outerWidth(el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);

width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
}

这正是 jquery 的 outerwidth 所做的,从::http://youmightnotneedjquery.com/ 抓取的可能对进一步发展很有趣

编辑:在 ie8 中,您必须使用 el.currentStyle[prop] 而不是 getComputedStyle(el);

关于javascript - 查找元素高度,包括边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29547940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com