這篇文章給大家分享的是有關(guān)js實(shí)現(xiàn)簡(jiǎn)易拖拽的案例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。
代碼實(shí)例
<div id="box" ></div> (function () { var dragging = false var boxX, boxY, mouseX, mouseY, offsetX, offsetY var box = document.getElementById('box') // 鼠標(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ì)超過可移動(dòng)范圍 var width = document.documentElement.clientWidth - box.offsetWidth var 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' } } // 釋放鼠標(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 } } })()
分享標(biāo)題:js實(shí)現(xiàn)簡(jiǎn)易拖拽的案例-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://aaarwkj.com/article10/dopggo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、微信小程序、企業(yè)建站、App開發(fā)、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容