Div高度在页面加载时输出为0
Div height outputting as 0 on page load?
我正在构建一个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
});
相关文章:
- 如何使用url加载程序在webpack中导入多个图像
- 如何在生成下载文件时显示加载动画
- 将“加载更多”添加到从Google电子表格中通过$.getJSON接收的数据输出中
- phantomjs - 在页面加载后执行Javascript函数,然后输出新的更改
- 刷新 php 输出而不重新加载页面
- 谷歌网络应用程序加载脚本不适用于HTML输出
- 分别设置输出文件夹和文件 url;带有 Django 的 Webpack 文件加载器
- 创建一个数组并输出其代码定义以进行预加载
- 如何在页面重新加载后输出jsignature
- 尝试将json输出加载到谷歌地图中
- 隐藏验证输出标记(✘)在加载/重新加载页面时隐藏符号
- 如何在不刷新、显示输出、重新加载表单、冲洗和重复的情况下提交表单
- 加载PHP输出的JS
- Div高度在页面加载时输出为0
- 提交表单而不刷新页面并将输出加载到html中
- 重新加载jQuery AJAX会复制JSON输出结果
- 如何不缓存加载器输出
- ASP.NET MVC4 显示模式不加载 TypeScript 输出
- 当从javascript文件加载css时,我应该如何保持html输出隐藏,直到css文件被加载
- 通过AJAX加载页面时输出Javascript变量