[英]Float a div at the bottom right corner, but not inside footer
我正在嘗試實現一個浮動在頁面右下角的“go to top”按鈕。 我可以使用以下代碼執行此操作,但我不希望此按鈕進入我的頁面的頁腳。 當用戶將頁面向下滾動到頁面底部時,如何阻止它進入頁腳並停留在頁眉頂部?
CSS
#to-top {
position: fixed;
bottom: 10px;
right: 10px;
width: 100px;
padding: 5px;
border: 1px solid #ccc;
background: #f7f7f7;
color: #333;
text-align: center;
cursor: pointer;
display: none;
}
JavaScript的
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#to-top').fadeIn();
} else {
$('#to-top').fadeOut();
}
});
$('#to-top').click(function() {
$('body,html').animate({scrollTop:0},"fast");
});
HTML
<div id="to-top">Back to Top</div>
編輯下面是它應該是什么樣子的圖。 黑色垂直矩形是滾動條。 “返回頂部”按鈕不應進入頁腳區域。
這是一個jsfiddle 。
事實證明,解決方案比我想象的要復雜得多。 這是我的解決方案。
它使用此功能檢查頁腳是否在屏幕上可見。 如果是,則將按鈕position: absolute
為div position: absolute
。 否則,它使用position: fixed
。
function isVisible(elment) {
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elment).offset().top;
return y <= (vpH + st);
}
$(window).scroll(function() {
if($(this).scrollTop() == 0) {
$('#to-top').fadeOut();
} else if (isVisible($('footer'))) {
$('#to-top').css('position','absolute');
} else {
$('#to-top').css('position','fixed');
$('#to-top').fadeIn();
}
});
增加bottom: 10px;
的價值bottom: 10px;
比頁腳的高度。 我現在看到了你的截圖,只是添加了一些填充底部。
$(document).ready(function(){
$(window).scroll(function(){
btnBottom = $(".btt").offset().top + $(".btt").outerHeight();
ftrTop = $(".footer").offset().top;
if (btnBottom > ftrTop)
$(".btt").css("bottom", btnBottom - ftrTop + $(".btt").outerHeight());
});
});
你忘了給z-index
,這可以防止它在頂部!
z-index: 999;
或者,如果它與頁面的頁腳重疊,則可以增加坐標。
bottom: 50px;
你的問題仍然不明確,“阻止它進入頁腳”。 它重疊了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.