2012-01-30 79 views
0

我有一個CSS模式的窗口,我用Javascript淡入。的HTML是這樣的:當背景被點擊時淡出Javascript「模式窗口」?

<div class="whiteout"> 
<div class="modal"> 
    <a class="modal-close" title="Close"></a> 
    // modal window content 
</div> 
</div> 

而CSS是這樣的:

.whiteout { 
    display: none; 
    position: fixed; 
    left: 0; top: 0; right: 0; bottom: 0; 
    background-color: #fff; 
    background-color: rgba(255, 255, 255, 0.7); 
} 
.modal { 
    position: fixed; 
    left: 50%; 
    top: 50%; 
    z-index: 200; 
    border: 12px solid #666; 
    border: 12px solid rgba(0, 0, 0, 0.5); 
    -moz-border-radius: 12px; 
    border-radius: 12px; 
} 

我使用jQuery來顯示模式窗口,當我點擊一個鏈接,用「白化」的背景下,當我點擊背景時我希望它淡出。

$('.share-link').click(function() { 
    $('.whiteout').fadeIn(); 
    return false; 
}); 
$('.whiteout').click(function() { // click the background 
    $(this).fadeOut(); 
}); 
$('.modal-close').click(function() { // close button on the modal window 
    $('.whiteout').fadeOut(); 
}); 

但是,無論何時點擊模式窗口以及背景,它都會淡出,因爲技術上這就是在「whiteout」元素中。當我點擊.modal元素時,是否有可能停止發生這種情況?

+1

不把這個作爲答案,因爲我沒有真的*查看你的具體情況: $('whiteout')。click(function(event){ if(this == event.target){ $(this).fadeOut();} }); ? – JimmiTh 2012-01-30 01:27:11

回答

4

試試這個:

$('.whiteout').click(function(e) { // click the background 
    if(e.target == this) 
     $(this).fadeOut(); 
}); 
+1

'if(e.target == this)'而不是?似乎更直接,並解決了將多個類應用於疊加層的可能性。 – gilly3 2012-01-30 01:33:04

+0

你是完全正確的先生,我會編輯我的答案 – 2012-01-30 01:34:25

+1

@ gilly3:同意(現在有人* *查看具體情況)。 'hasClass()'會稍微好一點,但是'if(e.target == this)'最適合顯示意圖 - 因爲它是檢查事件是否在jQuery中冒泡的標準方法(並且可能稍微快一點,好像有人在意)。 – JimmiTh 2012-01-30 01:39:46

0

最好的辦法可能是將白化DIV移動到身體的末端,完全超出了內容區域。使用正確的CSS,whiteout元素可以存在於DOM中的任何地方,但仍然可以達到正確的效果。

舉一個例子,看看jQuery UI’s dialog是如何工作的,它幾乎就是這樣。