如何使用javascript、jQuery當點擊DIV區塊外部背景將其DIV隱藏

11 月 29, 2018 | Javascript, | 0 條留言

使用Javascript

最流行的答案是沒有jQuery的解決方案:

Node.contains()方法返回一個Boolean值,該值指示節點是否是給定節點的後代,即節點本身,其直接子節點之一(childNodes),子節點直接子節點之一等等。

document.addEventListener('mouseup', function (e) {
    var container = document.getElementById('your container ID');

    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
}.bind(this));

使用jQuery

$(document).mouseup(function(e) 
{
    var container = $(YOUR CONTAINER SELECTOR);

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});