Comments: Write to a multi-layer Click Event listener. I think it is quite fun. So I extracted it from the module. For more information, see a recently written HTML5 game framework. Today, I wrote a multi-layer Click Event listener. I think it is quite fun. So we extracted it from the module. The following code is just a few ideas. The specific implementation is certainly not so ugly
The Code is as follows:
<! 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>