开发者

Strange combination of jQuery mouseenter, mouseleave, and append

开发者 https://www.devze.com 2023-03-26 12:35 出处:网络
I\'ve got an interesting issue with combining jQu开发者_如何学Cery\'s mouseenter and mouseleave events with a call to append.My object is to show extra content when the mouse enters something and then

I've got an interesting issue with combining jQu开发者_如何学Cery's mouseenter and mouseleave events with a call to append. My object is to show extra content when the mouse enters something and then remove it when the mouse leaves. It's very similar to what happens when you mouse over a tag here on StackExchange. The sequence is:

  • In mouseenter, create content and position it by the element under the mouse via .offset and .append.
  • In mouseleave, remove that content from the screen.

The element I'm operating on is an img, and I'm using jQuery 1.6.2. The problem is that .append somehow triggers mouseleave, which is quickly followed by .mouseenter, ad infinitum. It appears as a strange flickering effect on the content being added, as it's removed and re-added repeatedly. See an example here on jsFiddle. Why is this happening, and how do I resolve it?

EDIT: figured it out. D'oh. The added content was appearing under the mouse.


The reason this happens is that you're adding content where your mouse is. That new content is not part of your original element so by definition when you show the new DIV your mouse is not over the IMG any more.

One way to solve this would be to use the image as a background of a parent DIV and then append the new DIV to the parent so that the new DIV is a child of the parent.

On a side note is there a reason you chose not to use .hover()?

Here's a working jsfiddle for how I'd do this.

HTML:

<div class="papa">
    <div class='myDiv'>
        <div id='divHover'>Hello World</div>
    </div>
</div>

Javascript/Jquery:

$(document).ready(function() {
    $(".papa").hover(
      function () {
        $(".myDiv").show();
      },
      function () {
        $(".myDiv").hide();
      }
    );
});

CSS:

.papa {
    background-image:url('http://dummyimage.com/100x100/000/fff');
    height: 100px;
    width: 100px;
}
.myDiv {
    display: none;
    height: 30px;
    border: 1px solid black;
}
#divHover {
    width:100px;
    height:20px;
    background-color:white;
    border:1px solid black;
    position: relative;
    top: 10px;
    left: 10px;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号