最近寫一個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, < : 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 = {}; 🎜>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); <dl22 = function(evt) { <br />if(inside(evt.clientX, evt.clientY, getRect(l2))) { <br />console.log('click2'); <br />} <br />} <br />trigger.list.push(dl2); <br />