js實現(xiàn)限定范圍拖拽的示例
限定范圍拖拽
目錄
代碼實例 與簡易拖拽的差異 下載源碼鏈接代碼實例
* { padding: 0; margin: 0;}#box1 { width: 500px; height: 500px; background: #999; position: relative; left: 100px; top: 100px;}#box { width: 100px; height: 100px; background: #334; position: absolute; cursor: move;}<div id='box1'><div id='box'></div></div>(function () { var dragging = false var boxX, boxY, mouseX, mouseY, offsetX, offsetY var box = document.getElementById(’box’) var box1 = document.getElementById(’box1’) // 鼠標按下的動作 box.onmousedown = down // 鼠標的移動動作 document.onmousemove = move // 釋放鼠標的動作 document.onmouseup = up // 鼠標按下后的函數(shù),e為事件對象 function down(e) { dragging = true // 獲取元素所在的坐標 boxX = box.offsetLeft boxY = box.offsetTop // 獲取鼠標所在的坐標 mouseX = parseInt(getMouseXY(e).x) mouseY = parseInt(getMouseXY(e).y) // 鼠標相對元素左和上邊緣的坐標 offsetX = mouseX - boxX offsetY = mouseY - boxY } // 鼠標移動調(diào)用的函數(shù) function move(e){ if (dragging) { // 獲取移動后的元素的坐標 var x = getMouseXY(e).x - offsetX var y = getMouseXY(e).y - offsetY // 計算可移動位置的大小, 保證元素不會超過可移動范圍 // 此處就是父元素的寬度減去子元素寬度 var width = box1.clientWidth - box.offsetWidth var height = box1.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’ } } // 釋放鼠標的函數(shù) function up(e){ dragging = false } // 函數(shù)用于獲取鼠標的位置 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 } }})()
與簡易拖拽的差異
簡易拖拽的鏈接
可移動位置的改變
// 此處就是父元素的寬度減去子元素寬度var width = box1.clientWidth - box.offsetWidthvar height = box1.clientHeight - box.offsetHeight
下載源碼鏈接
星輝的Github
以上就是js實現(xiàn)限定范圍拖拽的示例的詳細內(nèi)容,更多關(guān)于js實現(xiàn)限定范圍拖拽的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python如何實現(xiàn)word批量轉(zhuǎn)HTML2. python excel和yaml文件的讀取封裝3. python3實現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)4. python爬蟲實戰(zhàn)之制作屬于自己的一個IP代理模塊5. moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決6. Android中的緩存7. 關(guān)于 Android WebView 的內(nèi)存泄露問題8. java——Byte類/包裝類的使用說明9. Python中內(nèi)建模塊collections如何使用10. Spring boot整合連接池實現(xiàn)過程圖解
