我有一个滚动到顶部的 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/