how remove next append on mouseleave?

2019-05-11 07:49发布

I have a problem with my code; when I mouseenter an element, a toolbar is appended to this element, but when I mouseleave from the toolbar to the element, the toolbar is appended again. How can I prevent this re-appending?

$('.el').on('mouseenter', function(e){

  var toolbar = $('<div class="toolbar"><span>leave toolbar to element</span></div>');  

    setTimeout(function(){
        toolbar.addClass('widget-over');
    },100);

    $('body').prepend(toolbar);

    toolbar.css({
        left:$('.el').offset().left,
        top:$('.el').offset().top - toolbar.height() - 20
    });

    $('.el').on('mouseleave',function(e){
        if ($(e.relatedTarget).closest(toolbar).length) return;
        toolbar.removeClass('widget-over');
        toolbar.remove();
    });

    toolbar.on('mouseleave',function(e){
        toolbar.remove();
    });
});

Big thanks to community for answers! exactly Jeremy Thille, Arun P Johny and Jivings

  1. Problem fiddle -> Fiddle
  2. Solution fiddle -> Fiddle

1条回答
孤傲高冷的网名
2楼-- · 2019-05-11 08:13

The trouble was that you were creating your event handlers each time there was a mouseover. I've split them up to make it simpler, and that seems to have fixed your bug:

var toolbar = $('<div class="toolbar"><span>leave toolbar to element</span></div>');  
toolbar.on('mouseleave',function(e){
    toolbar.remove();
});    

var enter = function(e) {

    setTimeout(function(){
        toolbar.addClass('widget-over');
    },100);

    $('body').prepend(toolbar);

    toolbar.css({
        left: $el.offset().left,
        top: $el.offset().top - toolbar.height() - 20
    });    
};

var leave = function(e){
    if ($(e.relatedTarget).closest(toolbar).length) return;
    toolbar.removeClass('widget-over');
    toolbar.remove();
}

var $el = $('.el')
    .on('mouseenter', enter)
    .on('mouseleave', leave);

JSfiddle: http://jsfiddle.net/3r8wrumL/2/

查看更多
登录 后发表回答