onscroll for div

2020-02-04 08:09发布

问题:

Does a div element not have an onscroll event handler? The behaviour on my page doesn't seem to indicate the div onscroll event handler is recognized.

<div id='bd' onscroll='alert("Scroll Called");'></div>

Also,
Do div scroll events roll up to window scroll events, as per DOM event bubbling ?

回答1:

Depending on which version of HTML you're using, you could use the onwheel event, instead.

The onscroll event works only if all the following are true:

  1. The div has overflow: auto, overflow: scroll, overflow-y: scroll, etc.
  2. The div currently has a visible scrollbar that can scroll.
  3. The mouse movement actually causes the scrollbar to scroll.

So the onscroll event is not really suited for detecting general mouse wheel movement.

Please note that the onwheel event is new in HTML 5. According to w3schools, it is pretty widely supported, though.



回答2:

I scratched my head on this one too, until I started learning more about DOCTYPE directives. The onscroll attribute is not supported in most recent version of the HTML spec. It'll show as invalid syntax in Visual Studio. It might work in many browsers, but it's still invalid code.

Instead, you canan event using Javascript or jQuery. I use an approach like this to synchronize scrolling on two separate div's:

$("#gridTableContainer").scroll(function() {
    HandlingScrollingStuff();
}); 


回答3:

Yes but the element needs to have a scrollbar. You can give it one with either overflow: auto (which gives you a scrollbar when the content is tall enough) or overflow: scroll. (These can be set specifically for x & y as well overflow-y: scroll...)

Although they don't bubble once the div has been scrolled to the bottom the window will start scrolling. (Basically if the div can scroll it will intercept the scroll event, but if it can't then it will go to the page)



回答4:

I know it may not be exactly what you're looking for, but a lot of javascript frameworks can help you with this. It is not necessary for the div to have a scrollbar for you to hook to the scroll events.

Eg. Mootools has the mousewheel event. Demo here. (It has scrollbars, but you can use Firebug to remove the scrollbars and try -- it still works).

I have used this myself on a site I made a while back. If you scroll while holding your mouse over the images it prevents the default page scrolling and instead slides the image-bar.



回答5:

JQUERY scroll() can help you.

$("#gridTableContainer").scroll(function() {
    HandlingScrollingStuff();
});