0

我正在制作具有通知“按钮”的网站。当用户单击此按钮时,通知 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>
4

3 回答 3

4

尝试这个:

$(document).mouseup(function (e)
{
    var myDiv = $("#theNotif");
    if (myDiv.has(e.target).length === 0)
        myDiv.hide();
});
于 2012-08-07T17:00:37.537 回答
2

怎么样:

$('#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并不像我最初想象的那么有用,因为它需要一些其他的解决方法。我使用它的原因是我不得不不断地听每一个文档点击,只是为了覆盖通知打开的场景。

相反,我决定使用绑定和取消绑定更简洁的方法。

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,在这种情况下关闭函数立即退出。

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

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

于 2012-08-07T17:00:40.017 回答
0

当鼠标移动到notifikasi时设置一个变量(比如a = 1),当移动到外面时取消设置。对于 Notif 也是如此。现在

$(document).click(function(){
    if(a == 0){
        if($('#theNotif').css('display') == 'block' || $('#theNotif').css('display') == ''){
            $('#theNotif').fadeOut('fast');
        }
    }
});
于 2012-08-07T17:20:29.877 回答