Ele*_*ing 3 html javascript css
我正在制作一个简单而有趣的绘图应用程序,其结构如下:
我试图使画布成为窗口的整个高度,减去页眉高度和页脚高度。
我已经尝试了多种方法,例如:
canvas.height = window.height - (document.getElementById("header").offsetHeight + document.getElementById("footer").offsetHeight);
Run Code Online (Sandbox Code Playgroud)
我什至尝试:
function getHeight(id) {
id = document.getElementById(id);
return id.offsetHeight + id.style.marginTop + id.style.marginBottom;
}
canvas.height = window.height - (getHeight("header") + getHeight("footer"))
Run Code Online (Sandbox Code Playgroud)
但无济于事。在控制台中,它id.style.marginTop只是返回了一个空字符串,尽管它的marginTop是在css中设置的……只是没有专门设置为marginTop,而是设置为margin: 8px 0 8px 0;
有什么方法可以在不使用jQuery的情况下获取元素的渲染高度,包括边距?
我假设我们必须margin: 8px 0 8px 0;使用id.style.margin... 将分隔成单独的变量,但是我不确定如何分隔它。
小智 6
function outerWidth(el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);
width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
}
Run Code Online (Sandbox Code Playgroud)
这确实符合jquery的外部宽度所做的工作,从:: http://youmightnotneedjquery.com/抓取 可能会引起进一步的发展
编辑:在ie8中,您必须使用el.currentStyle [prop]而不是getComputedStyle(el);。
您可以使用 flex 解决方案,而不必担心计算高度:
CSS:
.container {
display: flex;
flex-direction: column;
height: 100%;
}
canvas {
flex: 1;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div class="container">
<header>...</header>
<canvas>...</canvas>
<footer>...</footer>
</div>
Run Code Online (Sandbox Code Playgroud)