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

标签 javascript jquery html css

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

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

相关文章:

javascript - 如何为 anchor 实现通用点击事件

javascript - 返回javascript中两个字符串数组差异的函数

jquery - Ajax 调用未绑定(bind)所有模型属性

javascript - 检索 Canvas 上元素的 ID

html - 调整浏览器大小时使固定的 div 具有自由移动的文本

php - 这是处理信用卡付款的正确方法吗?

javascript - 如何添加类 ('overflow' );

javascript - 无法将 Rest JSON 数据绑定(bind)到 WinJS 中的 ListView 控件

javascript - 如何使用 Flow 泛型创建具有相同类型参数的泛型函数

jquery - 如何检测一个元素是否 float 在另一个元素下方?