JS for mouseover image upload button (like Faceboo

2019-08-20 05:36发布

问题:

I'm trying to build an image upload system like Facebook's where when you mouseover an image, a button (a div, not an actual html button) appears to select an image. So far, I'm using jQuery's hover method. The problem is, when I hover over the image, the button appears, but then when I hover over the button, the function assumes I'm no longer hovering over the image, and the button disappears. Of course then since the button is gone, I'm hovering over the image again and the button reappears. The end result is this sort of flickering effect when I move my mouse on the image.

I can't seem to figure out a way around it. I tried creating a separate hover event for the button itself that removes the hover event for the image and then replaces it on mouseout, but the image mouseout event seems to fire first, and it does nothing.

Only thing I can think is to use a setTimeout, but this seems sloppy. Seeing as Facebook is doing something similar, I'm sure there's a super clean way to handle it.

Any thoughts? Thanks!

回答1:

Try using mouseenter() instead of hover() to handle bubbling

The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.