jQuery 如何在浏览器打开和重新初始化时调整 div max-height

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11995665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:10:54  来源:igfitidea点击:

How to adjust div max-height on browser open and reinitialize

jqueryhtmlcss

提问by Anthony Russo

Okay I have a div class "content" and whenever the browser resizes to 800px in height the content div resizes its max-height to 500px. The problem I am having is if the browser opens with a height of 800px then there is no scrollbar for the div unless I refresh the browser.

好的,我有一个 div 类“内容”,每当浏览器将高度调整为 800 像素时,内容 div 都会将其最大高度调整为 500 像素。我遇到的问题是,如果浏览器以 800px 的高度打开,那么除非我刷新浏览器,否则 div 没有滚动条。

The code I have:

我有的代码:

<script type="text/javascript">
$(window).on('resize', function(){
if($(this).height() <= 800){
    $('.content').css('max-height', '500px'); //set max height
}else{
    $('.content').css('max-height', ''); //delete attribute
}
});
</script>

Also I am using jScrollPane and it works fine if I set the max-height in the css but if I use the code above instead a regular scrollbar is used. Any help on either would be appreciated.

此外,我正在使用 jScrollPane,如果我在 css 中设置了 max-height,它可以正常工作,但是如果我使用上面的代码而不是使用常规滚动条。任何帮助将不胜感激。

回答by undefined

Try this:

尝试这个:

$(document).ready(function() {

   $(window).on('resize', function(){
     if ($(this).height() <= 800){
          $('.content').css('max-height', '500px'); //set max height
     } else{
          $('.content').css('max-height', ''); 
     }
   }).resize()

})

回答by Hidde

Call that code once in $(document).ready().

$(document).ready().

回答by WebDevNewbie

Wrap it in

把它包起来

$(function() {
    //Script in here should run on document.ready
});