[英]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.