基于页面高度的滚动到顶部按钮的 CSS 条件

标签 css height

我有一个滚动到顶部的 jquery 按钮,单击该按钮将滚动到页面顶部。我只想在需要滚动时显示此按钮。

例如:如果页面/内容高度(不是窗口高度)超过 980px,则显示按钮。如果更少,隐藏按钮。

我如何使用纯 CSS 来做到这一点?谢谢。

最佳答案

我不确定您是否可以使用纯 CSS 来做到这一点。如果它取决于窗口高度,您可以使用媒体查询来实现。你可以使用这样的东西:

@media only screen and (max-height: 980px){
    #your-button-id{
        display:none;
    }
}

如果您希望它取决于内容的高度,您可以使用 Javascript。我给你的例子是在 jQuery 中,但你可以在没有 jQuery 的情况下做到这一点:

$(document).ready(function(){ // To make sure the DOM is loaded before you get the body's height
    if( $('body').height() < 980 )
        $('#your-button-id').css('display', 'none');
    else
        $('#your-button-id').css('display', 'block');

    $(window).resize(function(){ // To make sure that when window is resized, if you have media querys that modify the css and probably the body's height, you still hide the button if the height is no more than 980px
        if( $('body').height() < 980 )
            $('#your-button-id').css('display', 'none');
        else
            $('#your-button-id').css('display', 'block');
    }
}

更新:只要页面内容的高度大于窗口高度,您就可以显示按钮。在这种情况下,条件是

if( $('body').height() <= $(window).height() )

关于基于页面高度的滚动到顶部按钮的 CSS 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25494869/

相关文章:

jQuery Tabs 高度溢出我的其他 div

javascript - .height() 以百分比返回高度,如何以像素为单位获取它

css - 可滚动的 div 填充可用高度

css - 如何让设置高度的父包装器中的面板滚动而不同时更改父级的高度

html - 在失去焦点之前等待点击

css - 终端中的 LESS css 编译器帮助

css - 如何在 Firefox 中隐藏滚动条?

javascript - 如何获取页面可视部分的宽度和高度?

html - 2 div float 但高度相同

css - 在 Eclipse 中使用 HTML5 CSS