这很简单,但我还是个新手。
我有以下 HTML:
<div class="bg"></div>
<div class="jumbotron"></div>
<div class="container" id="main-cont">
....STUFF HERE....
</div>
</div>
我使用的图像是 2400px 高,我希望高度为窗口高度的 80%,所以我需要将 bg 的高度设置为等于 jumbotron 的高度。
这是我的 css 代码,它将显示我试图用 JS 完成的任务。
.bg {
position: fixed;
background-size: cover;
background: url('..//img/top-img.jpg') no-repeat center center;
z-index: -1;
width: 100%;
height: 600px;
top:0;
left:0;
}
.jumbotron {
height: 600px;
color: white;
background:transparent;
}
这是 JS。
<script>
$(document).ready(function() {
function setDivHeight() {
windowHeight = $(window).innerHeight()*0.8;
$('.jumbotron').css('height', windowHeight);
$('.bg').css('height', windowHeight);
};
});
</script>
我遇到的问题是 -
首先,我认为 JS 无法正常工作。
如果我向下滚动到一半并刷新页面,我的 CSS 就会出现问题。图片放在页面内容后面,看起来很难看。
最佳答案
如果 .jumbotron
的父元素是全高元素,您可以使用 calc:
height: calc(100% * 0.8);
或者只是基本的 CSS:
height: 80%;
但是support is a bit touchy .同样,您需要确保父对象的高度为 100%。
JavaScript 解决方案:
window.onload = function () {
function resize () {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
[].forEach.call(document.querySelectorAll('.jumbotron'), function (a) {
a.style.height = h * 0.8 + 'px';
});
}
window.onresize = resize;
resize();
};
Fiddle
jQuery 解决方案更简单一些:
$(window).resize(function () {
$('.jumbotron').css('height', $(window).height() * 0.8);
});
$(function(){ $(window).resize() });
Fiddle
关于javascript - 试图将我的 div 的高度设置为窗口高度的 80%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004361/