只点击空白处才隐藏div的方法

为了点击一个div层空白处时隐藏这个层,我写了这么个代码
onclick="this.style.display='none'
但是问题出来了,我按不空白的地方也它被隐藏。
比如我点击div层里的某个输入框也被隐藏,点按钮也是。
有什么办法点击不空白处事不隐藏,只点击空白处才隐藏div?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("*").click(function (event) {
            if (!$(this).hasClass("div")){
                $(".div").toggle();
            }
            event.stopPropagation(); //阻止事件冒泡    
        });
    });
</script>
<style type="text/css">
*{
    margin:0;
    padding:0;
    }
.div{
    width:200px;
    height:200px;
    position:absolute;
    top:50px;
    left:100px;
    background:#00BCF3;
    display:none;
    }
</style>
</head>
 
<body>
<input class="btn" type="button" value="点击"/>
<div class="div"></div>
</body>
</html>
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-11-07
js代理事件知道不,delegate,可以给父节点div绑定click事件,判断事件触发的目标元素event.target,如果是按钮,输入框之类的,就return,否则就是隐藏。追问

按你的意思是不是这样?
div.onclick=function () {
if( event.target!='textarea'&&event.target!='submit') this.style.display='none';
}
但还是不敢用。是不是按钮和输入框的target写错了?

第2个回答  2013-11-07
你绑定的DOM对象事件对不对,从你的描述没读明白你要实现什么!追问

我想要的是,按一个按钮的时候出现有输入框和提交按钮的小窗口层。然后按这个窗口外面的时候让它消失。我做的那个代码的记过无论按那个都让div层消失。按输入框也消失。有什么办法?

追答

给你一个思路

当鼠标点击按钮时弹出DIV,鼠标放在DIV上时用onmouseover,onmouseout记在一个变量里,如果鼠标在DIV上单击不隐藏DIV,如果不在DIV上单击就隐藏.

如:

var _flag = false; // 全局变量,用于记住鼠标是否在DIV上
document.getElementById('div').onmouseover = function (){
    _flag = true;
};

document.getElementById('div').onmouseout = function (){
    _flag = false;
};

document.body.onclick = function (){
    if(_flag){
        //不隐藏DIV
    }else{
        // 隐藏DIV
    }
};

// 没测试,你试下,这样也会导致一个DOM对象问题。

本回答被提问者采纳
相似回答