点击空白处隐藏div方法

来源:互联网 发布:mysql两表关联update 编辑:程序博客网 时间:2024/05/21 11:25

一般写法:

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事件

0 0