【问题标题】:100% Height Div with jQuery and CSS使用 jQuery 和 CSS 实现 100% 高度 Div
【发布时间】:2014-09-16 22:53:46
【问题描述】:

我一直在尝试在移动平台上创建一组整页 DIV,但没有成功。在 iOS 和 Android 设备上,第一个 DIV 可以正常显示,但即​​使我的边距设置为“0”,第二个 DIV 也会有上边距。

滚动到底部后,第一个 DIV 的红色仍然可见。

这是我用来复制问题的 JavaScript...

$(document).ready(function() {

    $(window).resize(function() {

        var newHeight = $(window).height();

        $('div').css({
            width: '100%',
            height: newHeight + 'px'
        });

    });

});

CSS...

        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            border: 0;
        }

        div {
            width: 100%;
            height: 100%;
        }

        .red {
            background: red;
        }

        .blue {
            background: blue;
        }

和 HTML...

<div class="red">
</div>

<div class="blue">
</div>

【问题讨论】:

  • 根据 jQuery 文档,您可以使用 css('height') 获得与 height() 相同的值,但包括单位,例如px.
  • 你的最终目标是什么?也许有更简单和不同的解决方案
  • this JSFiddle中工作正常...

标签: javascript android jquery html css


【解决方案1】:

为什么不直接使用 CSS?

.red, .blue{
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
}

【讨论】:

  • 会有多个 DIV,最终我会为滑块添加滑动功能和我自己的魔法酱。
  • 像这样定位的元素数量可以是任意的。 position:fixed 也适用于滑动面板:korynunn.github.io/flap
【解决方案2】:

我通过将 DIV 包装在容器 DIV 中并将溢出 x 设置为隐藏来解决此问题。

新的 CSS。

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    border: 0;
}

div#container {
    overflow-x: hidden;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    border: 0;
}

.red {
    width: 100%;
    height: 100%;
    background: red;
}

.blue {
    width: 100%;
    height: 100%;
    background: blue;
}

Javascript...

$(document).ready(function() {
    $(window).resize(function() {
        var winHeight = $(window).height(); winWidth = $(window).width();
        $('fp').css(function(){height : winHeight + " !important", width : winWidth + '!important'});
    });
});

它现在在移动和桌面浏览器中都运行良好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多