点击空白处隐藏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();// 调用取消冒泡方法
cancel_Bubble();
});
$("body").click(function(){
// 点击body时 隐藏 div
$("div").hide();
});行内写法:
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();// 调用取消冒泡方法
cancel_Bubble();
}function hideShow(obj) {
// 点击body时 隐藏 div
$(obj).hide();
}经测试,此法仅限于安卓机,如果要适配苹果手机,请使用touch事件
我是有底线的
扫描二维码手机查看该文章
文章引用:https://www.qinghuahulian.com/news/webzhishi/1394.html




