문제

I have a div that I want to be one of two sizes.

  • If browser window height is smaller than a given height, then it uses the smaller height for the div
  • However, if browser window height is larger than given height, then it uses larger height for the div

I tried the following code but it's not working. I need help to get it working.

Here is the jsbin: http://jsbin.com/oFIRawa/1

And here is the code I have so far:

page.html

<div id="theDiv">&nbsp;</div>

style.css

#theDiv {
    background: #000;
    border: 2px solid #222;
    width: 300px;
    height: 400px;
    margin: 50px auto 0 auto;
}

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);
        };
     })();
});
도움이 되었습니까?

해결책

You can do this in CSS my good sir. It's called responsive design!

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

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

This is more commonly used for max-width because it can tell us when someone is using a mobile device (something like 360px max-width), then we can modify our page to look nice on mobile. No fancy javascript needed!

다른 팁

var threshhold;
var smallerHeight = 50;
var largerHeight = 100;

if ($(window).height() < threshold)
    $('#theDiv').height(smallerHeight);
else
    $('#theDiv').height(largerHeight);

FIDDLE

Demo

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top