溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用js如何實(shí)現(xiàn)磁性吸附

發(fā)布時(shí)間:2020-10-27 13:59:41 來(lái)源:億速云 閱讀:244 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)使用js如何實(shí)現(xiàn)磁性吸附,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

代碼實(shí)例

* {
 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')

 // 鼠標(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.offsetLeft
 boxY = box.offsetTop

 // 獲取鼠標(biāo)所在的坐標(biāo)
 mouseX = parseInt(getMouseXY(e).x)
 mouseY = parseInt(getMouseXY(e).y)

 // 鼠標(biāo)相對(duì)元素左和上邊緣的坐標(biāo)
 offsetX = mouseX - boxX
 offsetY = mouseY - boxY
 }

 // 鼠標(biāo)移動(dòng)調(diào)用的函數(shù)
 function move(e){
 if (dragging) {
  // 獲取移動(dòng)后的元素的坐標(biāo)
  var x = getMouseXY(e).x - offsetX
  var y = getMouseXY(e).y - offsetY

  // 計(jì)算可移動(dòng)位置的大小, 保證元素不會(huì)超過(guò)可移動(dòng)范圍
  // 此處就是父元素的寬度減去子元素寬度
  var width = box1.clientWidth - box.offsetWidth
  var height = box1.clientHeight - box.offsetHeight

  // min方法保證不會(huì)超過(guò)右邊界,max保證不會(huì)超過(guò)左邊界
  x = Math.min(Math.max(0, x), width)
  y = Math.min(Math.max(0, y), height)

  // 磁性吸附部分
  if (x < RANGE) {x = 0}
  if (width - x < RANGE) {x = width}
  if (y < RANGE) {y = 0}
  if (height - y < RANGE) {y = height}

  // 給元素及時(shí)定位
  box.style.left = x + 'px'
  box.style.top = y + 'px'
 }
 }

 // 釋放鼠標(biāo)的函數(shù)
 function up(e){
 dragging = false
 }

 // 函數(shù)用于獲取鼠標(biāo)的位置
 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
 }
 }
})()

與限定范圍拖拽的差異

簡(jiǎn)易拖拽的鏈接

限定范圍拖拽的鏈接

添加磁性吸附部分

// 磁性吸附部分
if (x < RANGE) {x = 0}
if (width - x < RANGE) {x = width}
if (y < RANGE) {y = 0}
if (height - y < RANGE) {y = height}

關(guān)于使用js如何實(shí)現(xiàn)磁性吸附就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI