码迷,mamicode.com
首页 > 其他好文 > 详细

碰撞检测

时间:2017-11-29 16:12:22      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:javascrip   height   window   else   load   jpg   drag   capture   document   

html代码:

1 <div id="div1"></div>
2 <img src="img/1.jpg" id="img1">

css代码:

 1 #div1{
 2     width:100px;
 3     height:100px;
 4     background:red;
 5     position:absolute;
 6     z-index:2;
 7 }
 8 #img1{
 9     position:absolute;
10     left:500px;
11     top:200px;
12 }

javascript代码:

 1 window.onload = function(){
 2     var oDiv = document.getElementById("div1");
 3     var oImg = document.getElementById("img1");
 4     
 5     drag(oDiv);
 6     
 7     function drag(obj){
 8         obj.onmousedown = function(ev){
 9             var ev = ev || event;
10             
11             var disX = ev.clientX - this.offsetLeft;
12             var disY = ev.clientY - this.offsetTop;
13             
14             if(obj.setCapture){
15                 obj.setCapture();
16             }
17             
18             document.onmousemove = function(ev){
19                 var ev = ev||event;
20                 
21                 var L = ev.clientX - disX;
22                 var T = ev.clientY - disY;
23                 
24                 var L1 = L;
25                 var R1 = L + obj.offsetWidth;
26                 var T1 = T;
27                 var B1 = T + obj.offsetHeight;
28                 
29                 var L2 = oImg.offsetLeft;
30                 var R2 = L2 + oImg.offsetWidth;
31                 var T2 = oImg.offsetTop;
32                 var B2 = T2 + oImg.offsetHeight;
33                 
34                 if(R1<L2||L1>R2||B1<T2||T1>B2){
35                     oImg.src = "img/1.jpg";
36                 }else{
37                     oImg.src = "img/2.jpg";
38                 }
39                 
40                 obj.style.left = L + "px";
41                 obj.style.top = T + "px";
42             }
43             
44             document.onmouseup = function(){
45                 document.onmousemove = document.onmouseup = null;
46                 if(obj.releaseCapture){
47                     obj.releaseCapture();
48                 }
49             }
50             
51             return false;
52         }
53     }
54 }

 

碰撞检测

标签:javascrip   height   window   else   load   jpg   drag   capture   document   

原文地址:http://www.cnblogs.com/haishen/p/7920291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!