我试图使用jQuery中的.on()来捕获标记内的滚动事件。
所以这是我的解决方案:
getScrollTop()是一个返回顶部值的javascript函数(有效)
$(document).on("scroll#popup", '#popup', function(){
alert('scrolling');
$(".fixedHeader").css("position", "relative");
$(".fixedHeader").css("top", getScrollTop());
});
答案 0 :(得分:11)
混淆是“on()”如何运作。在jQuery中,当你说$(document).on(xx,“#popup”,yy)时,你试图在xx事件到达文档时运行yyy,但原始目标是“#popup”。
如果文档没有获得xx事件,那么这意味着它没有冒泡!详细信息在jQuery On文档中,但三个事件“加载”,“错误”和“滚动”不会冒泡DOM。
这意味着您需要将事件直接附加到接收它的元素。 $( “#弹出”)上(XX,YY)。
答案 1 :(得分:5)
事件只是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());
});
答案 2 :(得分:2)
正如@ Venar303所说,滚动不会冒泡,因此绑定到文档将无效。
使用此:
$('#popup').on('scroll', function() {});
而不是:
$(document).on('scroll', '#popup', function() {});