2012-04-28 2 views
1

모달 할 수있는 고전적인 방법은 콘텐츠 (대화 상자)와 Z- 색인 낮은 (오버레이) div 가진 div입니다 그런 다음 오버레이 클릭 이벤트를 바인딩 할 수 및 de 콘텐츠 대화 상자.외부를 클릭하여 div (모달)를 닫는 방법. Pinterest 및 페이 스북 방법

<div class="dialog">...</div> 
<div class="overlay" style="background-color:rgba(255, 255, 255, 0.9)"> 

그러나 나는 Pinterest와 Facebook이 그것을 하나의 div에 결합시킨 것을 알아 챘다.

<div class="overlay" style="background-color:rgba(255, 255, 255, 0.9);position: fixed; z-index: 9999;top: 0;right: 0;bottom: 0;left: 0;"> 
     <div class="dialog" style="position: static;"></div> 
</div> 

그러나이 방법에서는 대화 상자가없는 오버레이에서만 대화 상자를 닫으려면 클릭 이벤트를 어떻게 바인딩 할 수 있습니까? 이 같은 일을함으로써

http://jsfiddle.net/mCupS/9/

답변

7

:

$('.modal').click(function(){ 
    $('.modal, .inner').hide(); 
});          
$('.inner').click(function(e){ 
    e.stopPropagation(); 
});    
​ 

http://jsfiddle.net/mCupS/10/

event.stopPropagation()는 : DOM 트리를 버블 링 이벤트가 통지되는 모든 부모 핸들러를 방지에서 이벤트를 방지합니다.

+0

덕분에 완전히 – Luccas

+0

'인 stopPropagation()가'절대 권장하는 인 stopPropagation() (= 필수 항목 https://css-tricks.com/dangers-stopping-event-propagation/ – user664833

1

stopPropagation 부모 컨트롤에 이벤트 전파를 중지하고 모델 클릭 이벤트를받지 않습니다 :

$('.modal ').click(function(){ 
    alert("a"); 
}); 

$('.inner').click(function(e){ 
    alert("b"); 
    e.stopPropagation(); 
}); 

편집, 더 좋은 방법은 위를 달성했다.

The Dangers of Stopping Event Propagation에서 논의 된 바와 같이 위의 제안 된 해결 방법에 설명 된대로 더 나은 방법이있을 수 있습니다. 이 방법으로 내부 항목이 클릭으로 숨어 있지 않도록 할 수 있습니다.

Live Demo

$(document).on('click', function(event) { 
    if (!$(event.target).closest('.inner').length) { 
    $('.modal .inner').hide(); 
    } 
}); 
+0

답변을 주셔서 감사합니다 – Luccas

+0

당신은 환영합니다 – Adil

+0

'stopPropagation()'은 강력하게 권장하지 않습니다 ... https://css-tricks.com/dangers-stopping-event-propagation/ – user664833