开发者

jquery strange flickering on mouseover/out

开发者 https://www.devze.com 2022-12-26 09:30 出处:网络
The HTML: <div id=\"timerList\"> ... <li rel=\"project\" class=\"open\"> <a class=\"\" style=\"\" href=\"\"><ins>&nbsp;</ins>Project C</a>

The HTML:

<div id="timerList">
...
    <li rel="project" class="open">
        <a class="" style="" href=""><ins>&nbsp;</ins>Project C</a>
    </li>
...
</div>

The javascript/jquery:

$('#timerList li[rel="project"]').mouseover(function(){
    $('a:first',this).after('<span class="addNew"><a href="#">Add Timer</a></span>');
}).mouseout(function(){
    $('.addNew',this).remove();
});

When I hover my mouse over an li element, a span.addNew element is created within

THE PROBLEM: When I put my mouse ofer the span.addNew, it flickers on and off. Perhaps the mouseout event is firing, but I don't under开发者_StackOverflow中文版stand why it would or how to prevent it.

Thanks!


You can use the .hover() function, like this:

$('#timerList li[rel="project"]').hover(function(){
    $('a:first',this).after('<span class="addNew"><a href="#">Add Timer</a></span>');
}, function(){
    $('.addNew',this).remove();
});

.hover() is the same as using .mouseenter() and .mouseleave(). The mouseover and mouseout events fire when entering a child element, using mouseenter and mouseleave doesn't do this, eliminating the flicker, caused by removing and adding the span.

You can read more about the differences here:

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.


It's probably happening because jquery doesn't know that your new element is part of the DOM and thus doesn't recognize the mouseover. I'm not sure, but you might need jquery's live in this case.

Alternatively, instead of creating this element and then deleting it, you might want to create it up front but set display:none. Then hide / unhide the element.

0

精彩评论

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