最近写一个HTML5的游戏框架。今天写到一个多层点击事件的监听。觉得还是挺好玩的。于是把它从模块中抽化出来了。以下代码只是一些思想。具体实现肯定不是那么丑陋 复制代码代码如下: Document <br />.box > canvas { <br />position: absolute; <br />} <br /> <br />function getRect(obj) { <br />var x1 = obj.offsetLeft; <br />var y1 = obj.offsetTop; <br />var x2 = x1+obj.offsetWidth; <br />var y2 = y1+obj.offsetHeight; <br />return { <br />x1: x1, <br />y1: y1, <br />x2: x2, <br />y2: y2 <br />}; <br />} <br />function inside(x, y, rect) { <br />if(x>rect.x1 && x<rect.x2 && y>rect.y1 && y<rect.y2) { <br />return true; <br />} <br />else { <br />return false; <br />} <br />} <br />var trigger = {}; <br />trigger.list = []; <br />trigger.listen = function() { <br />var list = trigger.list; <br />document.addEventListener('click',function(evt) { <br />for(var i=0; i<list.length; ++i) { <br />list[i](evt); <br />} <br />}); <br />}; <br />trigger.listen(); <br />var l1 = document.getElementById('layer1'); <br />var l2 = document.getElementById('layer2'); <br />var dl1 = function(evt) { <br />if(inside(evt.clientX, evt.clientY, getRect(l1))) { <br />console.log('click'); <br />} <br />} <br />trigger.list.push(dl1); <br />var dl2 = function(evt) { <br />if(inside(evt.clientX, evt.clientY, getRect(l2))) { <br />console.log('click2'); <br />} <br />} <br />trigger.list.push(dl2); <br />