jQuery - 动态div高度

lem*_*mon 9 html css jquery height resize

我正在尝试调整页面加载和窗口大小调整div的大小.下面放置代码</body>,它在页面加载时工作正常,但在窗口大小调整时没有任何作用.我使用警报测试了resize函数,该调整在调整大小时触发,但高度保持不变.

<script type='text/javascript'>
    $('#main-content') .css({'height': (($(window).height()) - 361)+'px'});

    $(window).resize(function(){
        $('#main-content') .css({'height': (($(window).height()) - 361)+'px'});
        alert('resized');
    });
</script>
Run Code Online (Sandbox Code Playgroud)

更新:经过长时间休息后,我发现了导致问题的原因.我正在使用jquery脚本在正在调整大小的同一div上添加样式化滚动条.当我评论出来时,一切都很好.我已经在与调整大小相同的函数中移动了滚动条初始化,并尝试了我能想到的任何变化..仍然无法使其工作.

(#main-content div也有.scroll-pane类)

<script type='text/javascript'>
$(function(){
    $('#main-content').css({'height':(($(window).height())-361)+'px'});
    $('.scroll-pane').jScrollPane({scrollbarWidth:15, scrollbarMargin:15});

    $(window).resize(function(){
          $('#main-content').css({'height':(($(window).height())-361)+'px'});
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

lem*_*mon 14

解决了!

它只需要在计算高度之前删除jScrollPane并重新应用它.

<script type='text/javascript'>
$(function(){
    $('.scroll-pane').css({'height':(($(window).height())-361)+'px'});
    $('#main-content').jScrollPane({scrollbarWidth:15, scrollbarMargin:15});

    $(window).resize(function(){
          $('.scroll-pane').jScrollPaneRemove();
          $('#main-content').css({'height':(($(window).height())-361)+'px'});
          $('.scroll-pane').jScrollPane({scrollbarWidth:15, scrollbarMargin:15});
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)


Veg*_*sen 5

请注意,窗口调整大小功能仅在调整窗口大小后触发一次.它在调整大小操作期间不会更新,因此如果您要拖动窗口边框来测试它,则在松开鼠标按钮之前不会发生任何更改.

此外,请确保您在内部执行此操作$(document).ready(),如下所示:

<script type='text/javascript'>
$(function()
{
    $('#main-content') .css({'height': (($(window).height()) - 361)+'px'});

    $(window).resize(function(){
        $('#main-content') .css({'height': (($(window).height()) - 361)+'px'});
        alert('resized');
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

这是一个工作演示.