javascript 如何将自动高度定义为变量

ffx8fchx  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(89)

我试图把我的页脚下节div,节的高度是自动的,所以我不能定义一个顶部。
我尝试使用以下脚本定义高度:

function footer()
{
  var h = parseFloat(document.getElementById("sect").style.height);
  document.getElementById("foot").style.top = h + "px";
}

它不工作,因为它不读的高度作为数字,而是作为字符串'自动'。有可能做到这一点吗?有一个更好的方法来做到这一点?

nkoocmlb

nkoocmlb1#

如果我正确理解了你的问题,你想在javascript中找到你的元素的高度,那么下面是你的选择:

const elm = document.getElementById("sect");

// Returns an object with left, x, top, y, right, bottom, width, height properties of the element.
// width and height includes the border and padding. Others are relative to the top/left of the viewport
elm.getBoundingClientRect();

 // Viewable width/height of the element including padding, but NOT border, scrollbar or margin (excludes overflow)
elm.clientWidth;
elm.clientHeight;

// Viewable width/height of the element including padding, border, scrollbar, but NOT margin (excludes overflow)
elm.offsetWidth;
elm.offsetHeight;

// Entire width/height of the element including padding, but NOT border, scrollbar or margin (includes overflow)
elm.scrollWidth;
elm.scrollHeight;

所以你的函数可能看起来像:

function footer()
{
  var h = parseFloat(document.getElementById("sect").offsetHeight);
  document.getElementById("foot").style.top = h + "px";
}

相关问题