问题描述
我有以下观点
var FullWindow = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'detect_scroll');
},
// bind the events
events : {
"scroll" : "detect_scroll"
},
detect_scroll: function() {
console.log('detected');
}
});
我通过
var full_window = new FullWindow({el:$('body')});
但我认为它不起作用.
当我将事件更改为
events : {
"click" : "detect_scroll"
},
没关系.
怎么了?
推荐答案
我不认为 body
元素会触发滚动事件,除非您通过设置它的 overflow
属性在 CSS 中scroll
.来自 jQuery 文档:
I don't think that the body
element will fire a scroll event unless you explicitly give it a scrollbar by setting set its overflow
property to scroll
in CSS. From the jQuery docs:
当用户滚动到元素中的不同位置时,将向元素发送滚动事件.它适用于窗口对象,也适用于可滚动框架和溢出 CSS 属性设置为滚动的元素(或自动,当元素的显式高度或宽度小于其内容的高度或宽度时).
The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents).
假设您没有明确地为 body
元素提供带有 overflow:scroll
和/或固定高度的滚动条,scroll
您想要监听的事件可能是由 window
对象触发的,而不是 body
.
Assuming that you aren't explicitly giving the body
element a scrollbar with overflow:scroll
and/or a fixed height, the scroll
event you want to listen for is probably being fired by the window
object, not the body
.
我认为这里最好的方法是删除 Backbone 事件绑定(这实际上只是一个速记,仅适用于 view.el
元素内的事件)并直接绑定到窗口initialize()
:
I think the best approach here is to drop the Backbone event binding (which is really just a shorthand, and only works on events within the view.el
element) and bind directly to the window in initialize()
:
initialize: function() {
_.bindAll(this, 'detect_scroll');
// bind to window
$(window).scroll(this.detect_scroll);
}
这篇关于Backbone.js 检测滚动事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论