點擊空白處隱藏div元素的jQuery方法。
一般寫法:
html
<button id="btn">點我顯示div</button> <div>我是點擊btn后顯示的div</div>
jQuery
// 取消冒泡方法(兼容寫法)function cancel_Bubble() {
//如果事件對象存在
var event = event || window.event;// w3c的方法
if (event && event.stopPropagation) {
event.stopPropagation();
} else {// ie的方法
event.cancelBubble = true;
}
}
$("#btn").click(function(){
// 點擊按鈕時 顯示div
$("div").toggle();// 調(diào)用取消冒泡方法
cancel_Bubble();
});
$("body").click(function(){
// 點擊body時 隱藏 div
$("div").hide();
});行內(nèi)寫法:
html
<body onclick="hideShow(this)"><button onclick="showDiv(this)">點我顯示div</button><div>我是點擊btn后顯示的div</div></body>
jQuery
// 取消冒泡方法(兼容寫法)function cancel_Bubble() {
//如果事件對象存在
var event = event || window.event;// w3c的方法
if (event && event.stopPropagation) {
event.stopPropagation();
} else {// ie的方法
event.cancelBubble = true;
}
}function showDiv(obj) {
// 點擊按鈕時 顯示div
$(obj).siblings("div").toggle();// 調(diào)用取消冒泡方法
cancel_Bubble();
}function hideShow(obj) {
// 點擊body時 隱藏 div
$(obj).hide();
}經(jīng)測試,此法僅限于安卓機,如果要適配蘋果手機,請使用touch事件
我是有底線的
掃描二維碼手機查看該文章
文章引用:http://www.qingbaosc.com/news/webzhishi/1394.html




