JS实现判断碰撞的方法
本文实例讲述了JS实现判断碰撞的方法。分享给大家供大家参考。具体如下:
JS判断碰撞方法:
* @param obj 原对象
* @param dobj 目标对象
*/
function impact(obj, dobj) {
var o = {
x: getDefaultStyle(obj, 'left'),
y: getDefaultStyle(obj, ''),
w: getDefaultStyle(obj, 'width'),
h: getDefaultStyle(obj, 'height')
}
var d = {
x: getDefaultStyle(dobj, 'left'),
y: getDefaultStyle(dobj, ''),
w: getDefaultStyle(dobj, 'width'),
h: getDefaultStyle(dobj, 'height')
}
var px, py;
px = o.x <= d.x ? d.x : o.x;
py = o.y <= d.y ? d.y : o.y;
// 判断点是否都在两个对象中
if (px >= o.x && px <= o.x + o.w && py >= o.y && py <= o.y + o.h && px >= d.x && px <= d.x + d.w && py >= d.y && py <= d.y + d.h) {
return true;
} else {
return false;
}
}
/** 获取对象属性
* @param obj 对象
* @param attribute 属性
*/
function getDefaultStyle(obj, attribute) {
return parseInt(obj.currentStyle ? obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj, false)[attribute]);
}
示例如下:
<html>
<head>
<title> demo </title>
<style type="text/css">
body{margin:0px;}
.main{position:relative;}
#f1{position:absolute; background:#FF0000; :100px; left:100px; width:200px; height:200px; z-index:999}
#f2{position:absolute; background:#FFFF00; :0px; left:0px; width:600px; height:150px;}
</style>
</head>
<body>
<div class="main">
<div id="f1"></div>
<div id="f2"></div>
</div>
<script type="text/javascript">
var o = document.getElementById("f1");
var d = document.getElementById("f2");
alert(impact(o, d));
function impact(obj, dobj) {
var o = {
x: getDefaultStyle(obj, 'left'),
y: getDefaultStyle(obj, ''),
w: getDefaultStyle(obj, 'width'),
h: getDefaultStyle(obj, 'height')
}
var d = {
x: getDefaultStyle(dobj, 'left'),
y: getDefaultStyle(dobj, ''),
w: getDefaultStyle(dobj, 'width'),
h: getDefaultStyle(dobj, 'height')
}
var px, py;
px = o.x <= d.x ? d.x : o.x;
py = o.y <= d.y ? d.y : o.y;
// 判断点是否都在两个对象中
if (px >= o.x && px <= o.x + o.w && py >= o.y && py <= o.y + o.h && px >= d.x && px <= d.x + d.w && py >= d.y && py <= d.y + d.h) {
return true;
} else {
return false;
}
}
function getDefaultStyle(obj, attribute) {
return parseInt(obj.currentStyle ? obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj, false)[attribute]);
}
</script>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程