次の HTML の場合、これを行う 1 つの方法を次に示します。
<a href="#" class="modalShow">show modal</a> <a href="#" class="modalShow">show modal</a>
<div class="modal">
<span class="close">X</span>
<p>Some text in the first modal div</p>
</div>
<div class="modal">
<span class="close">X</span>
<p>Some text in the second modal div</p>
</div>
そしてCSS:
.modal {
display: none;
width: 50%;
padding: 0.5em;
min-height: 6em;
border: 10px solid #000;
border: 10px solid rgba(0,0,0,0.5);
position: absolute;
top: 20%;
left: 50%;
margin-left: -25%;
}
span.close {
display: none;
position: absolute;
top: -2.5em;
left: -2.5em;
width: 2em;
height: 2em;
text-align: center;
line-height: 2em;
border: 10px solid #000;
border: 10px solid rgba(0,0,0,0.5);
border-radius: 2em;
background-color: #fff;
cursor: pointer;
}
そしてjQuery:
$('a.modalShow').click(
function() {
// finds which link was clicked, and therefore which modal to show
var i = $(this).index('.modalShow');
// fades all the modal elements out
$('.modal').fadeOut(1000);
// fades the relevant modal in
$('.modal').eq(i).fadeIn(1000);
});
$('.modal').hover(
function() {
// while hovering over the modal, it fades the close element in after a delay
$(this).find('.close').delay(1000).fadeIn(500);
},
function() {
// after leaving/mouseout of the the modal, has a delay and then fades the close out
$(this).find('.close').delay(1000).fadeOut(500);
});
$('span.close').click(
function(){
// clicking the close span causes the closest ancestor modal to fadeout
$(this).closest('.modal').fadeOut(1000);
});
JS フィドルのデモ。
参考文献: