欢迎来到代码驿站!

jquery

当前位置:首页 > 网页前端 > jquery

js实现碰撞检测特效代码分享

时间:2021-08-16 09:20:46|栏目:jquery|点击:

自己做了碰撞检测的封装,先看下实例demo,在看封装

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>碰撞检测</title>
 <style type="text/css">
  *{
  margin: 0;
  padding: 0;
  }
  #divA,#divB{
  width: 200px;
  height: 200px;
  background-color: purple;
  font-size: 50px;
  line-height: 200px;
  text-align: center;
  position: absolute;
  color: #fff;
  }
  #divA{
  left: 30px;
  top: 30px;
  z-index: 5;
  }
  #divB{
  left: 300px;
  top: 300px;
  }
 </style>
 </head>
 <body>
 <div id="divA">A</div>
 <div id="divB">B</div>
 </body>
 <script type="text/javascript">
 var divA = document.getElementById("divA");
 var divB = document.getElementById("divB");
 
 
 divA.onmousedown = function (e) {
  
  var event1 = window.event || e;
  
  
  var startX = event1.clientX;
  
  var startY = event1.clientY;
  
  document.onmousemove = function (j) {
  
  var event2 = window.event || j;
  
  var endX = event2.clientX;
  var endY = event2.clientY;
  
  divA.style.left = divA.offsetLeft + (endX - startX) + "px";
  divA.style.top = divA.offsetTop + (endY - startY) + "px";
  
  startX = endX;
  startY = endY;
  
  if (isCrash(divA,divB) == true) {
   
   divA.style.backgroundColor = "red";
  } else{
   
   divA.style.backgroundColor = "purple";
  };
  }
 }
 
 
 divA.onmouseup = function () {
  
  document.onmousemove = null;
 }
 
 
 function isCrash (obj1,obj2) {
  
  var boolCrash = true;
  
  var left1 = obj1.offsetLeft;
  
  var right1 = obj1.offsetLeft + obj1.offsetWidth;
  
  var top1 = obj1.offsetTop;
  
  var bottom1 = obj1.offsetTop + obj1.offsetHeight;
  
  var left2 = obj2.offsetLeft;
  
  var right2 = obj2.offsetLeft + obj2.offsetWidth;
  
  var top2 = obj2.offsetTop;
  
  var bottom2 = obj2.offsetTop + obj2.offsetHeight;
  
  
  if (right1 > left2 && left1 < right2 && bottom1 > top2 && top1 < bottom2) {
  boolCrash = true;
  } else{
  boolCrash = false;
  }
  return boolCrash;
 }
 
 </script>
</html>

函数封装

 function isCrash (obj1,obj2) {
  
  var boolCrash = true;//假设true为碰撞
  
  var left1 = obj1.offsetLeft;
  
  var right1 = obj1.offsetLeft + obj1.offsetWidth;
  
  var top1 = obj1.offsetTop;
  
  var bottom1 = obj1.offsetTop + obj1.offsetHeight;
 
  var left2 = obj2.offsetLeft;
  
  var right2 = obj2.offsetLeft + obj2.offsetWidth;
  
  var top2 = obj2.offsetTop;
  
  var bottom2 = obj2.offsetTop + obj2.offsetHeight;
  
  
  if (right1 > left2 && left1 < right2 && bottom1 > top2 && top1 < bottom2) {
  boolCrash = true;
  } else{
  boolCrash = false;
  }
  return boolCrash;
 }

上一篇:jQuery中:checkbox选择器用法实例

栏    目:jquery

下一篇:jQuery的css()方法用法实例

本文标题:js实现碰撞检测特效代码分享

本文地址:http://www.codeinn.net/misctech/167207.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有