简体   繁体   English

使元素至少等于视口的高度

[英]Make an element at least the height of the viewport

What I'd like to do is have sections (all other content inside) for a one page layout. 我想做的是为一个页面布局设置部分(内部所有其他内容)。 Some of these sections don't have enough content to reach all the way to the bottom of a screen on desktop, but if I set a 'magic number' value in CSS (ie min-height:1000px) you'd be scrolling forever when viewing on a phone. 这些部分中的某些部分内容不足,无法一路到达桌面上的屏幕底部,但是如果我在CSS中设置“幻数”值(即min-height:1000px),则您将永远滚动在手机上查看时。 Inversely, I don't want to cut off conent that extends past viewport height. 相反,我不想切断超出视口高度的内容。 JavaScript is definitely not my strong point, but here is my (likely god awful) attempt with Jquery: JavaScript绝对不是我的强项,但这是我(可能很糟糕)使用Jquery的尝试:

$(document).ready(function () {
    //make sections at least as tall as the viewport
    $(window).height(function () {
        if ('section'.height <= window.height) {
            $('section').css('height', window.height);
        }
    });
});

Anyone know a better way? 有人知道更好的方法吗? How far off (/or being stupid) am I? 我有多远(或愚蠢)? Anything is appreciated. 一切都赞赏。

Try 尝试

$(document).ready(function () {
    //make sections at least as tall as the viewport

    var $sections = $('section').each(function(){
        var $this = $(this);
        $this.data('oheight', $this.height())
    });

    $(window).resize(function(){
        var winheight = $(window).height();
        $('section').each(function(){
            var $this = $(this), oheight = $this.data('oheight') || $this.height();
            $this.css('height', oheight <= winheight ? winheight : oheight);

            //remove this
            $this.find('.height').text(oheight <= winheight ? winheight : oheight)
        })
    }).resize()

});

Demo: Fiddle 演示: 小提琴

Why not just use CSS to do this? 为什么不仅仅使用CSS来做到这一点呢? jsFiddle jsFiddle

body, html, section {
    width:100%;
    height:100%;
}

为什么不为每个视图(桌面,移动设备,...)分开样式?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM