我正在制作带有通知"按钮"的网站。当用户单击此按钮时,通知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
在这里并不像我最初想象的那么有用,因为它需要一些其他解决方法。我使用它的原因是,它让我不得不不断收听每一次文档点击,只是为了覆盖打开通知的情况。
相反,我决定使用绑定和取消绑定更简洁的方法是使用绑定。
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
的子元素,在这种情况下,close函数会立即退出。
否则,它将继续关闭通知,然后立即取消绑定侦听器。
请注意,您必须使用命名函数,而不是在jQuery中可能习惯的匿名内联函数,以便能够正确解绑它。
当鼠标移到 notifikasi 上时设置一个变量(比如 a=1),当移动到外面时取消设置它。同样适用于通知。现在
$(document).click(function(){
if(a == 0){
if($('#theNotif').css('display') == 'block' || $('#theNotif').css('display') == ''){
$('#theNotif').fadeOut('fast');
}
}
});