gpt4 book ai didi

javascript - 试图将我的 div 的高度设置为窗口高度的 80%

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:50 24 4
gpt4 key购买 nike

这很简单,但我还是个新手。

我有以下 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>

我遇到的问题是 -

  1. 首先,我认为 JS 无法正常工作。

  2. 如果我向下滚动到一半并刷新页面,我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com