[英]JQuery: Unable scroll to bottom of page when using addClass & removeClass
我有以下代碼,它在滾動時添加類“ sticky”,並在元素到達錨點“#search-anchor”時刪除類“ sticky”。
但是,我無法一直向下滾動以查看完整的頁腳。 有什么想法嗎?
https://jsfiddle.net/coldfusion/6z6q3kxm/2/
<style>
header,footer {height:50px;background-color:red;}
section {height: 50px; background-color: yellow;}
#search-anchor {background-color:blue;}
.body {height:1600px;background-color:black;}
.sticky {
position: fixed;
bottom: 0px;
width: 1000px;
margin-right: auto !important;
margin-left: auto !important;
z-index: 999;
}
</style>
<script>
jQuery(document).ready(function() {
var a = jQuery(".inline-search").offset().top,
n = function() {
var n = jQuery(window).scrollTop(),
n = n + 10;
n > a ? jQuery(".inline-search").addClass("sticky") : jQuery(".inline-search").removeClass("sticky")
};
n(), jQuery(window).scroll(function() {
n()
})
}),
jQuery(document).ready(function() {
var search = $(".inline-search");
$(window).scroll(function() {
var anchorPosition = $("#search-anchor").offset().top;
var navHeight = $(".inline-search").height();
var navPosition = $(".inline-search").offset().top;
if ((navPosition + navHeight) >= anchorPosition) {
search.removeClass('sticky');
}
})
});
</script>
<header>HEADER</header>
<section class="inline-search">
</section>
<div class="body"></div>
<section id="search-anchor">
</section>
<footer>FOOTER</footer>
如果使用指令debugger
暫停控制台中JavaScript的執行,您將確切地了解@ mike-mccaughan的解釋。
由於CSS position:fixed;
您的腳本從文檔流中添加了元素.inline-search
並將其刪除position:fixed;
。
如果向下滾動並向文檔流中重新添加.inline-search
,文檔高度將再次更改,並且滾動條具有一些空間,因此用於檢測我們是否位於頁面底部的代碼將不再起作用。 發生的事情是無限快速地循環添加和重新添加您的固定位置:因此,頁面似乎在到達頁腳之前“停止”滾動。
為了創建這樣的效果(滾動時固定定位),我建議使用Bootstrap的附加jQuery插件。 更進一步:Bootstrap最近宣布,由於CSS的粘性定位,他們將放棄Affix,因此,真正的“面向未來”的建議是將粘性定位與polyfill結合使用,以使較舊的瀏覽器具有相同的效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.