1

ブール値を使用して子要素がクリックされたかどうかを判断するのは悪い考えでしょうか? より良い方法はありますか?

注: これには 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);

}
4

1 に答える 1

1

クリックの原因を知りたい場合は、 を確認してくださいevent.target。IE6-8 では、window.event.srcElementプロパティを確認します。

if ( document.body.addEventListener ) {
  document.body.addEventListener("click", alertMe, false);
} else if ( document.body.attachEvent ) {
  document.body.attachEvent("onclick", alertMe);
}

function alertMe(event) {
  console.log( event.target || window.event.srcElement.nodeName );
}

そのため、イベントを にアタッチしている間に、によって(場合によっては)、どの子がクリックをトリガーしたかdocument.bodyを判断できます。targetsrcElement

デモ: http://jsbin.com/oxuzek/7/edit

于 2012-05-02T20:05:49.530 に答える