[英]Scroll event never fires and .scrollTop() always returns 0 because of wrapper DIV
Basically what I'm trying to do is use a on scroll event and use jquery scrollTop() while using this [off-canvas menu][1] 基本上我想做的是在使用此[off-canvas菜单] [1]时使用on scroll事件并使用jquery scrollTop()
Here's a fiddle! 这是小提琴! http://jsfiddle.net/k6hsvp1a/
http://jsfiddle.net/k6hsvp1a/
Here's the code that isn't working as expected: (The scroll event never fires and scrollTop() always returns as 0) 以下是无法正常运行的代码:(scroll事件从不触发,scrollTop()始终返回0)
$( window ).on('scroll', function() {
console.log($(window).scrollTop());
console.log('scrolling!');
});
My understanding is that because the off-canvas menu uses a relatively positioned wrapper div, the scroll event never fires because $(window).scrollTop() always returns zero. 我的理解是,由于画布菜单使用相对定位的包装器div,因此$(window).scrollTop()始终返回零,因此不会触发滚动事件。
How can I make a scroll event work and use scrollTop() ? 如何使滚动事件工作并使用scrollTop()?
Debugging time... this is a little heavy handed, but worked in this scenario: 调试时间...这有点费力,但是在这种情况下有效:
$("*").on('scroll', function() {
console.log($(this));
});
The "*"
applies to all elements. "*"
适用于所有元素。
Checked out the console: 检出控制台:
[div.st-content, context: div.st-content, jquery: "1.9.1", constructor: function, init: function, selector: ""…]
[div.st-content,上下文:div.st-content,jquery:“ 1.9.1”,构造函数:函数,init:函数,选择器:“”…]
So our scroll event is being triggered by .st-content 所以我们的滚动事件是由.st-content触发的
$(".st-content").on('scroll', function() {
console.log($(this).scrollTop());
console.log("scrolling");
});
Your fiddle is fiddling with the wrong container. 您的小提琴摆弄着错误的容器。 Check my update here:
在这里检查我的更新:
http://jsfiddle.net/k6hsvp1a/1/ http://jsfiddle.net/k6hsvp1a/1/
This is the difference: 区别在于:
$( '.st-content' ).on('scroll', function() {
console.log($('.st-content').scrollTop());
console.log('scrolling!');
});
Every block element can scroll independently if its contents are larger than its dimensions and set to overflow: scroll
(or overflow: auto
(or overflow-y
or... you get the point)). 如果每个块元素的内容大于其尺寸并设置为
overflow: scroll
(或overflow: auto
(或overflow-y
或...您明白了),则可以独立overflow: scroll
)。
The scroll event then fires on the actual div that's scrolling, and doesn't bubble up to the window. 然后,scroll事件会在实际滚动的div上触发,并且不会冒泡到窗口。 ( https://developer.mozilla.org/en-US/docs/Web/Events/scroll )
( https://developer.mozilla.org/en-US/docs/Web/Events/scroll )
What's also confusing is that this div
in particular also happens to take up the whole window, so it looks like it's the window that's scrolling. 同样令人困惑的是,这个
div
也恰好占据了整个窗口,因此看起来好像是正在滚动的窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.