Jquery Popup - 如何在切换事件旁边模糊或删除

时间:2013-05-31 11:23:14

标签: jquery css

我已经制作了一个弹出菜单,可以在点击时切换。我想保留此功能,但也添加了单击页面中任何其他位置以删除该类的功能。

非常感谢任何帮助。请参阅下面的代码和演示

DEMO

HTML

<div class="tree-wrapper">
    <div class="example-wrapper">
        <a href="#" class="toggle-popup">Toggle</a>
    </div>
    <span id="popup">
        <ol>
            <li class="new-folder"><a href="#">New Folder</a></li>
            <li class="delete"><a href="#">Delete</a></li>
            <li><a href="#">Rename</a></li>
            <li><a href="#">Cut</a></li>
            <li><a href="#">Copy</a></li>
            <li class="disabled"><a href="#">Paste</a></li>
        </ol>
    </span>
</div>

JS

var popupToggle = $(".tree-wrapper .toggle-popup");

$(function () {

    popupToggle.click(function(e) {
        var popupToggleLink = $(this);
        e.preventDefault();
        popupToggleLink.toggleClass("open");
        popupToggleLink.closest(".tree-wrapper").find("#popup").toggleClass("open").css('left',e.pageX).css('top',e.pageY);
    });

});

CSS

#popup {
    display: none;
}
#popup.open {
    display: block;
}

2 个答案:

答案 0 :(得分:1)

你可以这样做:

$(document).click(function (e) {
    // Your code here
    if ($(e.target).closest('.tree-wrapper').length !== 0) return;
    $(".tree-wrapper").find("#popup").removeClass("open");
    popupToggle.removeClass("open");
});

FIDDLE DEMO

答案 1 :(得分:1)

event.stopPropagation()可用于防止事件在点击链接后冒泡到document对象。在document对象上添加事件处理程序以隐藏弹出窗口。

此外,我在弹出窗口中添加了一个事件处理程序,因此您仍然可以单击弹出窗口中的链接。与popupToggle.click()

的原理相同
var popup = $("#popup"),
    popupToggle = $(".tree-wrapper .toggle-popup");

$(function () {
    // toggle popup but don't bubble the event to the document
    popupToggle.click(function(e) {
        e.stopPropagation();
        popup.toggleClass("open").css({ left: e.pageX, top: e.pageY});
    });

    // keep toggle open but don't bubble event to document
    popup.click(function(e){
        e.stopPropagation();
    });

    // close popup when clicked on document
    $(document).click(function(){
        popup.toggleClass("open", false);
    });
});

DEMO: http://jsfiddle.net/tive/5fKEu/