如何用 js 原生代码实现 jquery 的 outerHeight 方法?

最近准备用 Zepto 代替 jquery 了,替换之后发现 outerHeight 这个方法没有,自己大概了解一下,怕写不全面,想请问一下有大神知道如何使用 js 原生代码实现不?谢谢。

阅读 2.3k
3 个回答

关键点在于如何获取margin的值:

// element为dom元素
// options为true时,表示需要获取外边距
function outerHeight(element, options) {
  const offsetHeight = element.offsetHeight;

  if (options) {
    // 是否要计算外边距
    const { marginTop, marginBottom } = window.getComputedStyle(
      element,
      null
    );
    return (
      offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10)
    );
  }
  return offsetHeight;
}

使用:

console.log(outerHeight(document.querySelector(".content"))); // 280
console.log(outerHeight(document.querySelector(".content"), true)); // 326

image.png

jQuery是开源的,去看看它是怎么实现的不就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题