ブール値を使用して子要素がクリックされたかどうかを判断するのは悪い考えでしょうか? より良い方法はありますか?
注: これには 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);
}