单击下一个项目时如何显示工具栏(并隐藏当前)?

时间:2015-02-09 07:06:50

标签: javascript jquery html

当我点击下一个相似元素时如何显示工具栏(并隐藏当前)?在我的代码中,当我点击下一个相似的元素时,工具栏不会消失,只有当我首先点击主体然后在元素上时,他才会消失,如何删除工具栏而不点击身体来显示下一个工具栏?谢谢! http://jsfiddle.net/wwL8fgr1/1/

$(".element").on('mouseup', function(e){

        $('[el-button]').click(function(e){
            e.preventDefault();
        });

        var toolbar  = $('<div class="dm-popover"></div>');

        if ( !$('.dm-popover').hasClass('in') ) {
            setTimeout(function(){
                toolbar.addClass('in');
            },100);
            $('body').prepend(toolbar);
        }

        toolbar.addClass('dm-link-frontend-control-top');

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

        setTimeout(function(){
            $('body').on('mouseup', function(e){
                if($(e.target).closest(toolbar).length == 0){
                    $('body').unbind('click', arguments.callee);
                        toolbar.removeClass('in');
                        toolbar.remove();
                }
            });
        }, 100);

        e.stopPropagation();
});

2 个答案:

答案 0 :(得分:0)

负责删除工具栏的代码在这里:

$('body').on('mouseup', function(e){
    if($(e.target).closest(toolbar).length == 0){
        $('body').unbind('click', arguments.callee);
        toolbar.removeClass('in');
        toolbar.remove();
    }
});

请注意,这会在mouseup上注册body处理程序。这就是您需要点击body以删除工具栏的原因。您可以将此处理程序附加到第二个元素,如果这是您所期望的。

修改

我的猜测是你希望在this fiddle中实现类似的目标。请注意,它仅适用于2个元素,如果您需要更多类似元素,您可能需要创建一个函数来为您生成id而不是将它们存储在{ {1}}属性。

我的意见:

您的代码似乎过于复杂 - 您正在使用超时,交换css,data-而不是mouseup,每次点击都会创建click元素,从而阻止处理程序传播...尝试通过删除不必要的东西来简化它。

答案 1 :(得分:0)

你可以试试这个

$(".element").on('mouseup', function(e){

            $('[el-button]').click(function(e){
                e.preventDefault();
            });

            if ( !$('.dm-popover').hasClass('in') ) 
            {
                var toolbar  = $('<div class="dm-popover"></div>');
                setTimeout(function(){
                    toolbar.addClass('in');
                },100);
                $('body').prepend(toolbar);
            }
            else
            {
                var toolbar  = $('.dm-popover');
            }    

            toolbar.addClass('dm-link-frontend-control-top');

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

            setTimeout(function(){
                $('body').on('mouseup', function(e){
                    if($(e.target).closest(toolbar).length == 0){
                        $('body').unbind('click', arguments.callee);
                            toolbar.removeClass('in');
                            toolbar.remove();
                    }
                });
            }, 100);

            e.stopPropagation();
        });

请参阅JSFiddle http://jsfiddle.net/wwL8fgr1/3/