//?點擊按鈕,DIV彈出隱藏
$('#btn1').toggle(function(){
$('#div1').show();
},function(){
$('#div1').hide();
});
//?點擊按鈕,DIV彈出,點擊body任意地方隱藏div
$('#btn2').click(function(){
if?(?event?&&?event.stopPropagation?)?{?
//?this?code?is?for?Mozilla?and?Opera?
event.stopPropagation();?
}?
else?if?(window.event)?{?
//?this?code?is?for?IE?
window.event.cancelBubble?=?true;?
}
$('#div2').show();
});
$(document).click(function(){
$('#div2').hide();
});
});
以上都必須要基於,div的css是合理的。
其中?event.stopPropagation(); 和?window.event.cancelBubble = true; 是阻止事件冒泡的寫法,建議自行百度學習。
css:(這裏用了fixed,不考慮兼容性)
/*?水平垂直居中的div?*/#div1,#div2{
position:?fixed;
top:?50%;
left:?50%;
background:red;
width:100px;
height:100px;
margin:-50px?0?0?-50px;
display:none;
}
同樣的功能有很多插件,例如fancybox,fancyzoom等