使用布尔值来确定是否单击了子元素会是一个坏主意吗?有没有更好的方法?
注意:我不想为此使用 jquery。
请参见下面的代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body{margin:0;}
#container{height:300px;background:red}
#box{width:500px;height:300px;background:blue;margin:auto}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
<script>
var hbWindow = window,
hbDocument = document,
hbBooleanIfIsOutside = new Boolean(),
hbIdBox = hbDocument.getElementById('box'),
hbIdContainer = hbDocument.getElementById('container');
hbWindow.onload = function () {
hbIdContainer.onclick = function () {
if(hbBooleanIfIsOutside) {
alert('you\'re outside!');
} else {
alert('you\'re inside!');
}
hbBooleanIfIsOutside = true;
}
hbIdBox.onclick = function () {
hbBooleanIfIsOutside = false;
}
}
</script>
</body>
</html>
添加了新版本:
在这个版本中,我改用 addEventListener。
var hbWindow = window,
hbDocument = document,
hbIdBox = hbDocument.getElementById('box'),
hbIdContainer = hbDocument.getElementById('container');
hbWindow.onload = function () {
function inOrOut(e){
if (!e) e = hbWindow.event;
if((e.target || e.srcElement).id == 'container') {
alert('you\'re outside!');
} else {
alert('you\'re inside!');
}
}
hbIdContainer.addEventListener('click', inOrOut, false);
}