2013-05-13 36 views
0

我有一個簡單的模式對話框打開這樣的:面向較低層到關閉模式對話框

<div id="social" class="overlay"> 
    <div class="inner"> 
    <a class="close" href="#"><span class="icon-close"></span></a> 

    CONTENT 

</div> 
</div> 

這裏的CSS:

.overlay { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    z-index: 100; 
    background: fade(@black, 75%); 
    display: none; 
    z-index: 999; 
} 

#social .inner { 
    margin: 0 auto; 
    z-index: 1000; 
    width: 380px; 
} 

這裏是JS:

$(document).ready(function(){ 
    $("#social").css("height", $(document).height()); 

    $(".social").click(function(){ 
     $("#social").fadeIn(); 
     return false; 
    }); 

    $(".close").click(function(){ 
     $("#social").fadeOut(); 
     return false; 
    }); 
}); 

當有人點擊與類close的鏈接時,模式框關閉。我想模態框關閉時,有人點擊模式框外的任何地方,所以覆蓋層(z-index:999)的任何地方。我不知道如何定位底層(z-index:999)而不會影響頂層(z-index:1000)。

我對jQuery不太瞭解,所以如果你能以新手的方式說出你的建議,那會很棒。謝謝! :)

回答

1

通過在疊加層上附加單擊事件處理程序,可以在疊加層單擊時淡出模式框。 JSFiddle

HTML

<input type="button" class="social" value="test" /> 
<div id="social" class="overlay"> 
    <div class="inner"> 
     <a class="close" href="#"> 
      <span class="icon-close">X</span> 
     </a> 
     CONTENT 
    </div> 
</div> 

CSS

.overlay { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    z-index: 100; 
    background: rgba(0, 0, 0, 0.5); 
    display: none; 
    z-index: 999; 
} 
#social .inner { 
    margin: 0 auto; 
    z-index: 1000; 
    width: 380px; 
} 

jQuery的

$(document).ready(function() { 

    $("#social").css("height", $(document).height()); 

    $(".social").click(function() { 
     $("#social").fadeIn(); 
     return false; 
    }); 

    $(".close").click(function() { 
     $("#social").fadeOut(); 
     return false; 
    }); 


    //This is the part that handles the overlay click 
    $("#social").on('click', function (e) { 
     if (e.target == this) { 
      $(this).fadeOut(); 
     } 
    }); 
}); 
+0

爲編輯@KilianStinson謝謝! – 2013-05-13 11:48:52

+0

謝謝!但是,當我點擊內容(實際的模式框)時,這也會關閉模式框。我只希望它在模式框外部即在背景上單擊時關閉。 – 2013-05-13 12:14:42

+0

啊,你的編輯使它工作。非常感謝! :) – 2013-05-13 12:19:42