why doesn't delegate work for scroll?

2020-01-29 06:06发布

I am trying to use jquery delegate to bind to scroll events.

html

<div id='parent'>
        <div id='child'>Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah </div>
</div>

css

#parent {
width:200px;
height:200px;
border:2px solid black;
overflow:auto;        
}
#child {
width:300px;
height:300px;
background:red;    
}

javascript

$('#parent').delegate('#child', 'scroll', function(){
alert(this)
}) 

jsfiddle

http://jsfiddle.net/C6DRR/1/

Why doesn't it work?

3条回答
男人必须洒脱
2楼-- · 2020-01-29 06:44

why doesn't delegate work for scroll?

Because scroll event doesn't bubble through the DOM.

But, on modern browsers (IE>8), you can capture scroll event to e.g document level or any static container for dynamic element. You have to use javascript addEventListener() method passing true as useCapture parameter, jQuery doesn't support capturing phase:

Note: in your example, scroll event happen to #parent level, not #child

document.addEventListener('scroll', function (event) {
    if (event.target.id === 'parent') { // or any other filtering condition        
        console.log('scrolling', event.target);
    }
}, true /*Capture event*/);

-DEMO-

For explanation on difference between event capture/propagation, see here or there.

Be aware, a captured event is always fired before any other bubbling event of same kind.

查看更多
萌系小妹纸
3楼-- · 2020-01-29 06:56

i think this may bind your scroll

$('#child').live('keyup', function() {
var el = $(this);
if (!el.data("has-scroll")) {
    el.data("has-scroll", true);
    el.scroll(function(){
       //doscrollaction(el);
    });
}
doscrollaction(el);
});

as requested by op:

i change the css so child overflows and use jquery.scroll and that works, however there is no 'scroll' event like you have for jquery not that i know of anyway, hence the reason why bin, live etc can not be set for scroll and also why your deligate will not work

查看更多
姐就是有狂的资本
4楼-- · 2020-01-29 06:56

Because scroll event does not bubble. http://www.quirksmode.org/dom/events/scroll.html

查看更多
登录 后发表回答