Div高度在页面加载时输出为0

Div height outputting as 0 on page load?

本文关键字:输出 加载 高度 Div      更新时间:2023-09-26

我正在构建一个shopify主题。这里有一个div重叠的例子。如果左div比右div短(绝对位置),则右div会按预期与其下的div重叠。

为了解决这个问题,我试过写一些js在这个jsFiddle中工作,但在我的实际网站中,div的高度输出为0,因此该函数不起作用。对于我的生活,我不明白为什么高度为左和右潜水将是0,不知道是否有人可以提供一些启示?

JS

var productImgHeight = $('.left').outerHeight(),
productInfoHeight = $('.right').outerHeight(),
gap = productInfoHeight - productImgHeight;
if (productImgHeight < productInfoHeight) {
    alert(productImgHeight);
    $('.left').css({"margin-bottom":gap+"px"});
} else {
    $('.left').css({"margin-bottom":"0"});
}

提前感谢!

如果你的内容是隐藏元素(无显示或隐藏可见性),那么你的高度将始终为0,我找到的唯一方法是:

  • 用一个样式为- position:fixed; left:100%
  • 的类将元素从页面上隐藏
  • 获取负载高度
  • 用js隐藏元素并移除类
  • 设置渐变

var productImgHeight = $('.left').outerHeight(),
  productInfoHeight = $('.right').outerHeight(),
  gap = productInfoHeight - productImgHeight;
if (productImgHeight < productInfoHeight) {
  console.log(productImgHeight);
  $('.left').css({
    "margin-bottom": gap + "px"
  });
} else {
  $('.left').css({
    "margin-bottom": "0"
  });
}
$('.container').hide().removeClass('fixed').fadeIn()
.fixed {
  position: fixed;
  left: 100%;
  top: 100%;
}
.container {
  position: relative;
}
.left {
  width: 400px;
  height: 400px;
  background-color: blue;
  opacity: 0.5;
}
.right {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 15;
  width: 300px;
  height: 500px;
  background-color: green;
  opacity: 0.5;
}
footer {
  width: 100%;
  height: 200px;
  background-color: pink;
  opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container fixed">
  <div class="left">Left
  </div>
  <div class="right">Right
  </div>
  <footer>Footer</footer>
</div>

更新小提琴

您的DOM必须完全加载才能使这些函数工作。将其封装在jQuery提供的ready函数中:

$(document).ready(function () {
    var productImgHeight = $('.left').outerHeight(),
        productInfoHeight = $('.right').outerHeight(),
        gap = productInfoHeight - productImgHeight;
    if (productImgHeight < productInfoHeight) {
        alert(productImgHeight);
        $('.left').css({"margin-bottom":gap+"px"});
    } else {
        $('.left').css({"margin-bottom":"0"});
    }
});

Also:确保元素没有被display: none;隐藏,因为-它没有高度。你可以绕过这个设置来显示(不可见),获取高度,然后再次隐藏它。

$('.left').css({
    display: "block",
    opacity: 0 //Invisible to user
});
var productImgHeight = $('.left').outerHeight();
$('.left').css({
    display: "none",
    opacity: 1
});