js 實(shí)現(xiàn)碰撞檢測(cè)的示例
碰撞檢測(cè)
目錄
代碼實(shí)例 與簡(jiǎn)易拖拽的差異 下載源碼鏈接代碼實(shí)例
<div style='background: #334;width: 100px;height: 100px;position: absolute;cursor: move;z-index: 999;'></div><div style='background: green;width: 100px;height: 100px;position: absolute;top: 200px;left: 500px;'></div>(function () {var dragging = falsevar boxX, boxY, mouseX, mouseY, offsetX, offsetYvar box = document.getElementById(’box’)var box2 = document.getElementById(’box2’)var box2X, box2Y// 鼠標(biāo)按下的動(dòng)作box.onmousedown = down// 鼠標(biāo)的移動(dòng)動(dòng)作document.onmousemove = move// 釋放鼠標(biāo)的動(dòng)作document.onmouseup = up// 鼠標(biāo)按下后的函數(shù),e為事件對(duì)象function down(e) {dragging = true// 獲取元素所在的坐標(biāo)boxX = box.offsetLeftboxY = box.offsetTop// 獲取元素box2所在的坐標(biāo)box2X = box2.offsetLeftbox2Y = box2.offsetTop// 獲取鼠標(biāo)所在的坐標(biāo)mouseX = parseInt(getMouseXY(e).x)mouseY = parseInt(getMouseXY(e).y)// 鼠標(biāo)相對(duì)元素左和上邊緣的坐標(biāo)offsetX = mouseX - boxXoffsetY = mouseY - boxY}// 鼠標(biāo)移動(dòng)調(diào)用的函數(shù)function move(e){if (dragging) {// 獲取移動(dòng)后的元素的坐標(biāo)var x = getMouseXY(e).x - offsetXvar y = getMouseXY(e).y - offsetY// 計(jì)算可移動(dòng)位置的大小, 保證元素不會(huì)超過可移動(dòng)范圍var width = document.documentElement.clientWidth - box.offsetWidthvar height = document.documentElement.clientHeight - box.offsetHeight// min方法保證不會(huì)超過右邊界,max保證不會(huì)超過左邊界x = Math.min(Math.max(0, x), width)y = Math.min(Math.max(0, y), height)// 給元素及時(shí)定位box.style.left = x + ’px’box.style.top = y + ’px’// 碰撞檢測(cè)// x坐標(biāo)值的范圍判斷,y坐標(biāo)值的范圍判斷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('碰撞到')}}}// 釋放鼠標(biāo)的函數(shù)function up(e){dragging = false}// 函數(shù)用于獲取鼠標(biāo)的位置function getMouseXY(e){var x = 0, y = 0e = e || window.eventif (e.pageX) {x = e.pageXy = e.pageY} else {x = e.clientX + document.body.scrollLeft - document.body.clientLefty = e.clientY + document.body.scrollTop - document.body.clientTop}return {x: x,y: y}}})()
與簡(jiǎn)易拖拽的差異
簡(jiǎn)易拖拽的鏈接
碰撞檢測(cè)
// 碰撞檢測(cè)// x坐標(biāo)值的范圍判斷,y坐標(biāo)值的范圍判斷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 實(shí)現(xiàn)碰撞檢測(cè)的示例的詳細(xì)內(nèi)容,更多關(guān)于js 碰撞檢測(cè)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JavaWeb Servlet中url-pattern的使用2. jsp中sitemesh修改tagRule技術(shù)分享3. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼4. React優(yōu)雅的封裝SvgIcon組件示例5. 輕松學(xué)習(xí)XML教程6. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除9. ASP基礎(chǔ)知識(shí)VBScript基本元素講解10. 詳解瀏覽器的緩存機(jī)制
