最近寫一個(gè)HTML5的游戲框架。今天寫到一個(gè)多層點(diǎn)擊事件的監(jiān)聽(tīng)。覺(jué)得還是挺好玩的。于是把它從模塊中抽化出來(lái)了。以下代碼只是一些思想。具體實(shí)現(xiàn)肯定不是那么丑陋
代碼如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box > canvas {
position: absolute;
}
</style>
</head>
<body>
<div class="box">
<canvas id="layer1" width="200" height="200"></canvas>
<canvas id="layer2" width="500" height="500"></canvas>
</div>
<script type="text/javascript">
function getRect(obj) {
var x1 = obj.offsetLeft;
var y1 = obj.offsetTop;
var x2 = x1+obj.offsetWidth;
var y2 = y1+obj.offsetHeight;
return {
x1: x1,
y1: y1,
x2: x2,
y2: y2
};
}
function inside(x, y, rect) {
if(x>rect.x1 && x<rect.x2 && y>rect.y1 && y<rect.y2) {
return true;
}
else {
return false;
}
}
var trigger = {};
trigger.list = [];
trigger.listen = function() {
var list = trigger.list;
document.addEventListener('click',function(evt) {
for(var i=0; i<list.length; ++i) {
list[i](evt);
}
});
};
trigger.listen();
var l1 = document.getElementById('layer1');
var l2 = document.getElementById('layer2');
var dl1 = function(evt) {
if(inside(evt.clientX, evt.clientY, getRect(l1))) {
console.log('click');
}
}
trigger.list.push(dl1);
var dl2 = function(evt) {
if(inside(evt.clientX, evt.clientY, getRect(l2))) {
console.log('click2');
}
}
trigger.list.push(dl2);
</script>
</body>
</html>
更多信息請(qǐng)查看IT技術(shù)專欄