如果浏览器高度小于给定的像素数,如何更改div高度?

Acc*_*tor 0 html javascript css height window-resize

我有一个div,我想成为两种尺寸之一.

  • 如果浏览器窗口高度小于给定高度,则它使用较小的div高度
  • 但是,如果浏览器窗口高度大于给定高度,则它使用较大的div高度

我尝试了以下代码,但它不起作用.我需要帮助才能让它发挥作用.

这是jsbin:http://jsbin.com/oFIRawa/1

这是我到目前为止的代码:

page.html中

<div id="theDiv">&nbsp;</div>
Run Code Online (Sandbox Code Playgroud)

style.css文件

#theDiv {
    background: #000;
    border: 2px solid #222;
    width: 300px;
    height: 400px;
    margin: 50px auto 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

的script.js

$(document).ready(function () {
    // call the method one time
    updateWindowSize();
    // subscribe the method to future resize events
    $(window).resize(updateWindowSize);

    // variables
     var updateWindowSize = (function(){
        var minAllowedWindowHeight = 500;
        var largerDivHeight = 400;
        var smallerDivHeight = 300;

        // actual updateWindowSize function
        return function(){
            var winHeight = $(window).height();
            var newHeight = winHeight < minAllowedWindowHeight ? smallerDivHeight : largerDivHeight;
            $('#theDiv').height(newHeight);
        };
     })();
});
Run Code Online (Sandbox Code Playgroud)

小智 5

你可以用CSS做我的好先生.它被称为响应式设计!

@media (max-height:500px) {
    Enter special css conditions for 500px height.
}

@media (max-height:200px) {
    Enter special css conditions for 200px height.
}
Run Code Online (Sandbox Code Playgroud)

这通常用于最大宽度,因为它可以告诉我们何时有人使用移动设备(类似360px max-width),然后我们可以修改我们的页面以在移动设备上看起来不错.不需要花哨的JavaScript!