Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

jquery - Hover, mouseover and mouse out

I'm learning and using jQuery and want to display a delete icon for some elements.

I have an outer main div, which contains number of wrappers for elements. Inside the element wrapper, I want to display a delete icon when the user hovers over the element wrapper, and remove it when user moves out of the element wrapper.

Using mouseover and mouseout, I can display and remove the icon, but as soon as I move my mouse over the delete icon it is removed because it fires the mouseout event for the element wrapper. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two options for you:

  1. CSS's :hover pseudo-class (but only if you don't have to support IE6)
  2. mouseenter and mouseleave events

CSS's :hover pseudo-class

You can make the browser do all the work if you don't need IE6 support, by using the :hover pseudo-class:

/* Don't show `child` elements inside `parent` elements...*/
parent child {
    display: none;
}

/* ...unless the `parent` element is being hovered over */
parent:hover child {
    display: block; /* or inline-block or whatever */
}

Live example

However, IE6 doesn't support the :hover pseudo-class except on a elements. IE7+ and all recent other browsers do.

mouseenter and mouseleave events

If CSS doesn't do it for you, you're looking for the mouseenter and mouseleave events, which are IE-specific but emulated by jQuery on all other browsers. jQuery even has a convenient function, hover, for hooking up handlers to both events so you can readily accomplish what you're looking to do.

$(...your parent element...).hover(
    function() {
        // Called when the mouse enters the element
    },
    function() {
        // Called when the mouse leaves the element
    }
 );

Here's a complete live example:

HTML:

<div>Hover over me <span class='del'>[X]</span></div>
<div>And me <span class='del'>[X]</span></div>
<div>And me <span class='del'>[X]</span></div>

JavaScript using jQuery:

$('div').hover(
  function() {
    $(this).find('span.del').show();
  },
  function() {
    $(this).find('span.del').hide();
  }
);

The reason you had trouble with mouseover and mouseout is that they bubble, and so your mouseout handler on your parent element was seeing the bubbled mouseout from the underlying element when your mouse moved into the delete element. mouseenter and mouseleave don't bubble, and so they don't have that problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...