[英]Performance problems when user scrolls to bottom of the page
我有一個固定在頁面右下方的按鈕;
.btn-this{
width: 313px;
height: 61px;
background-color: #ebb762;
position: fixed;
bottom: 0;
right: 0;
z-index: 99;
}
所以我想在頁面的某個位置滾動后將按鈕的位置從“固定”更改為“相對”。
現在,起初我為我完成了這項工作:
JQuery(function ($) {
var masinfo = $(".btn-this");
$(window).scroll(function () {
var scroll = $(window).scrollTop();
if (scroll >= 457) {
masinfo.css('position', 'relative');
} else {
masinfo.css({
position: 'fixed',
bottom: '0'
});
}
});
});
但是后來我確實看到這不是一個高質量的解決方案,因為我將不得不粘貼並更改每個頁面的代碼,而且這將永遠不會很順利。
所以我確實檢查了這兩個帖子:
檢查用戶是否已滾動到底部
到達父容器底部的“ #sidebar”類時,如何添加“ bottom”類?
但是話又說回來,我無法使其順利運行,代碼可以正常工作,但是執行時間很多,
使用時:
if ($(window).scrollTop() + $(window).height() > $(document).height() - 78) {
console.log('bottom');
}
控制台記錄“底部” 11次;
我試過使用去抖器,但是我只是不理解這個概念,或者只是沒有正確地使用它。
有人能做這樣的事嗎?
防反跳功能限制了該功能可以觸發的速率。 閱讀有關反跳功能的更多信息還有另外一種方法可以改善requestAnimationFrame的動畫/滾動性能
所以你的函數可以寫成
JQuery(function ($) {
var masinfo = $(".btn-this");
$(window).scroll(function () {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup the new requestAnimationFrame()
timeout = window.requestAnimationFrame(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 78) {
console.log('bottom');
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.