繁体   English   中英

当用户单击通知分区外的任何地方时,使通知分区消失

[英]Make Notification Div Fade Out When User Click Anywhere Outside The Notification Div

我正在制作带有通知“按钮”的网站。 当用户单击此按钮时,通知div将出现在按钮的底部。

我想使其行为类似于在Facebook中的通知。 当用户单击通知div元素外部的任意位置时,通知将消失。

到目前为止,我已经成功地使通知div在单击通知按钮时淡入和淡出。 我正在使用jQuery来做到这一点。

但是,当用户单击通知div之外的任何地方时,我不知道如何使其淡出。

谁能帮我?

这是我编写的代码:

<div id="notifikasi" style="position:relative; cursor:pointer">Notification<sup style="padding: 2px 4px 2px 4px; background: red"></sup>
    <div id="theNotif" style="position: absolute; top: 20px; left: 0px; background: #fff; color: #000; border: solid 1px #999; z-index: 999; padding: 10px 20px 10px 0px; width:200px; display:none">
        <ul>
            <li>Some Notification</li>
            <li>Some Notification</li>
            <li>Some Notification</li>
        </ul>
    </div>
</div>

<script>
$('#notifikasi').click(function(){
    if($('#theNotif').css('display') == 'none'){
        $('#theNotif').fadeIn('fast');
    }
    else{
        $('#theNotif').fadeOut('fast');
    }
});
</script>

尝试这个:

$(document).mouseup(function (e)
{
    var myDiv = $("#theNotif");
    if (myDiv.has(e.target).length === 0)
        myDiv.hide();
});

怎么样:

$('#notifikasi').click(function(){
    $('#theNotif').fadeIn('fast', function() {
        $(document).one('click', function(e) {
            $('#theNotif').fadeOut('fast');
        });
    });
});

// prevent triggering when clicking the actual notification
$('#theNotif').click(function() { return false; });​

演示版

通知消失后,将向文档添加一个一次性单击侦听器,以监听任何单击。


编辑

我自己玩了.one ,得出的结论是: .one并没有我最初想象的那么有用,因为它需要其他一些解决方法。 我之所以使用它,是因为让我不得不不断地聆听每一次文档单击,这只是为了覆盖打开通知的情况,这使我感到恼火。

相反,我决定一种更整洁的方法是使用bind和unbind。

function closeNotification(e) {
   if($(e.target).closest('#theNotif').length > 0) {
      // notification or child of notification was clicked; ignore
      return;
   }

   $('#theNotif').fadeOut('fast');
   $(document).unbind('click', closeNotification);
};

$('#notifikasi').click(function(){
    $('#theNotif').fadeIn('fast', function() {
        $(document).bind('click', closeNotification);
    });
});

演示版

上面的代码在概念上与原始代码非常相似。 淡入后,单击侦听器将注册到文档。 这次,将文档单击侦听器中进行检查,以查看所单击的元素是#theNotif还是#theNotif的子#theNotif ,在这种情况下,关闭函数将立即退出。

否则,它将继续关闭通知,然后立即取消绑定监听器。

请注意,您必须使用一个命名函数,而不是您可能在jQuery中使用过的匿名内联函数,才能正确地解除绑定。

当鼠标移到notifikasi上时设置一个变量(例如a = 1),当鼠标移到notifikasi上时取消设置。 对于NotNot同样。 现在

$(document).click(function(){
    if(a == 0){
        if($('#theNotif').css('display') == 'block' || $('#theNotif').css('display') == ''){
            $('#theNotif').fadeOut('fast');
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM