[英]How to use JQuery .on() to catch the scroll event
我正在嘗試使用jQuery中的.on()來捕獲標記內的滾動事件。
所以這是我的解決方案:
getScrollTop()是一個返回頂部值的javascript函數(有效)
$(document).on("scroll#popup", '#popup', function(){ alert('scrolling'); $(".fixedHeader").css("position", "relative"); $(".fixedHeader").css("top", getScrollTop()); });
困惑在於“on()”的工作原理。 在jQuery中,當你說$(document).on(xx,“#popup”,yy)時,你試圖在xx事件到達文檔時運行yyy,但原始目標是“#popup”。
如果文檔沒有獲得xx事件,那么這意味着它沒有冒泡! 詳細信息在jQuery On文檔中,但三個事件“加載”,“錯誤”和“滾動”不會冒泡DOM。
這意味着您需要將事件直接附加到接收它的元素。 $( “#彈出”)上(XX,YY)。
事件只是scroll
,而不是scroll#popup
。
// http://ejohn.org/blog/learning-from-twitter
// Also, be consistent with " vs '
var $fixedHeader = $('.fixedHeader').css('position', 'relative');
$(document).on('scroll', '#popup', function() {
console.log('scrolling'); // you *really* don't want to alert in a scroll
$fixedHeader.css("top", getScrollTop());
});
正如@ Venar303所說,滾動不會冒泡,因此綁定到文檔將無法正常工作。
用這個:
$('#popup').on('scroll', function() {});
而不是這個:
$(document).on('scroll', '#popup', function() {});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.