js 实现碰撞检测的示例
#代码知识 发布时间: 2026-01-12
碰撞检测

目录
- 代码实例
- 与简易拖拽的差异
- 下载源码链接
代码实例
<div id="box" style="background: #334;width: 100px;height: 100px;position: absolute;cursor: move;z-index: 999;"></div>
<div id="box2" style="background: green;width: 100px;height: 100px;position: absolute;top: 200px;left: 500px;"></div>
(function () {
var dragging = false
var boxX, boxY, mouseX, mouseY, offsetX, offsetY
var box = document.getElementById('box')
var box2 = document.getElementById('box2')
var box2X, box2Y
// 鼠标按下的动作
box.onmousedown = down
// 鼠标的移动动作
document.onmousemove = move
// 释放鼠标的动作
document.onmouseup = up
// 鼠标按下后的函数,e为事件对象
function down(e) {
dragging = true
// 获取元素所在的坐标
boxX = box.offsetLeft
boxY = box.offsetTop
// 获取元素box2所在的坐标
box2X = box2.offsetLeft
box2Y = box2.offsetTop
// 获取鼠标所在的坐标
mouseX = parseInt(getMouseXY(e).x)
mouseY = parseInt(getMouseXY(e).y)
// 鼠标相对元素左和上边缘的坐标
offsetX = mouseX - boxX
offsetY = mouseY - boxY
}
// 鼠标移动调用的函数
function move(e){
if (dragging) {
// 获取移动后的元素的坐标
var x = getMouseXY(e).x - offsetX
var y = getMouseXY(e).y - offsetY
// 计算可移动位置的大小, 保证元素不会超过可移动范围
var width = document.documentElement.clientWidth - box.offsetWidth
var height = document.documentElement.clientHeight - box.offsetHeight
// min方法保证不会超过右边界,max保证不会超过左边界
x = Math.min(Math.max(0, x), width)
y = Math.min(Math.max(0, y), height)
// 给元素及时定位
box.style.left = x + 'px'
box.style.top = y + 'px'
// 碰撞检测
// x坐标值的范围判断,y坐标值的范围判断
var judge_x = (x >= box2X - box2.offsetWidth) && (x <= box2X + box2.offsetWidth)
var judge_y = (y >= box2Y - box2.offsetHeight) && (y <= box2Y + box2.offsetHeight)
if (judge_x && judge_y) {
console.log("碰撞到")
}
}
}
// 释放鼠标的函数
function up(e){
dragging = false
}
// 函数用于获取鼠标的位置
function getMouseXY(e){
var x = 0, y = 0
e = e || window.event
if (e.pageX) {
x = e.pageX
y = e.pageY
} else {
x = e.clientX + document.body.scrollLeft - document.body.clientLeft
y = e.clientY + document.body.scrollTop - document.body.clientTop
}
return {
x: x,
y: y
}
}
})()
与简易拖拽的差异
简易拖拽的链接
碰撞检测
// 碰撞检测
// x坐标值的范围判断,y坐标值的范围判断
var judge_x = (x >= box2X - box2.offsetWidth) && (x <= box2X + box2.offsetWidth)
var judge_y = (y >= box2Y - box2.offsetHeight) && (y <= box2Y + box2.offsetHeight)
if (judge_x && judge_y) {
console.log("碰撞到")
}
下载源码链接
星辉的Github
以上就是js 实现碰撞检测的示例的详细内容,更多关于js 碰撞检测的资料请关注其它相关文章!
代码知识SEO上一篇 : C# 操作网络适配器的示例
下一篇 : C#表达式目录树示例详解
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!