查找元素高度,包括边距 [英] Find element height, including margin

查看:66
本文介绍了查找元素高度,包括边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making a simple and fun drawing app, and in it the structure is as follows:

  • 标题
  • 画布
  • 脚步

我正在尝试使画布成为窗口的整个高度,减去页眉高度和页脚高度.

I'm trying to get the canvas to be the full height of the window, minus the header height and footer height.

我已经尝试了多种方法,例如:

I've tried multiple things like:

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 8px0;

But to no avail. In the console id.style.marginTop just returned an empty string, although its marginTop is set in the css... just not set specifically to marginTop, it's set as margin: 8px 0 8px 0;

是否有任何方法可以在不使用jQuery的情况下获取元素的显示高度(包括边距)?

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

I'm assuming we'd have to separate the margin: 8px 0 8px 0; into separate variables, using id.style.margin... but I'm just not sure how to separate it.

推荐答案

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

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

这完全符合jquery的外部带宽所做的工作,从以下网址抓取到::: http://youmightnotneedjquery.com/可能会引起进一步发展的兴趣

this does exactly what jquery's outerwidth is doing, scratched from ::http://youmightnotneedjquery.com/ might be interteresting for further develpoment

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

EDIT: in ie8 you have to use el.currentStyle[prop] instead of getComputedStyle(el);

这篇关于查找元素高度,包括边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆