我有一个div,我想成为两种尺寸之一。
如果浏览器窗口的高度小于给定的高度,则它将较小的高度用于div
但是,如果浏览器窗口的高度大于给定的高度,则它将使用更大的div高度
我尝试了以下代码,但无法正常工作。我需要帮助才能正常工作。
这是jsbin:http://jsbin.com/oFIRawa/1
这是我到目前为止的代码:
page.html
<div id="theDiv"> </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);
};
})();
});
最佳答案
您可以在CSS上做到这一点,先生。这就是所谓的响应式设计!
@media (max-height:500px) {
Enter special css conditions for 500px height.
}
@media (max-height:200px) {
Enter special css conditions for 200px height.
}
这通常用于max-width,因为它可以告诉我们何时有人使用移动设备(例如360px max-width),然后我们可以修改页面以在移动设备上看起来不错。不需要花哨的JavaScript!
关于javascript - 如果浏览器高度小于给定像素数,如何更改div高度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19428525/