您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)javascript如何實(shí)現(xiàn)拖曳互換div的位置的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
利用dom元素的dragstart/ondragover/ondrop事件完成,在拖曳開(kāi)始的時(shí)候獲取到拖曳元素,然后允許拖動(dòng),最后鼠標(biāo)抬起后放到新的位置;這里用到了event.preventDefault()方法,很多人可能比較疑惑,這里簡(jiǎn)單介紹一下
event.preventDefault() :該方法是讓瀏覽器不要執(zhí)行與事件關(guān)聯(lián)的默認(rèn)動(dòng)作
我們?cè)赿ragover事件中使用,因?yàn)閐ragover關(guān)聯(lián)的默認(rèn)動(dòng)作是阻止將數(shù)據(jù)或者元素放置到其他元素中;所以需要通過(guò)event.preventDefault()禁止該默認(rèn)事件,這樣就可以允許拖動(dòng)元素到新的位置了
<!-- div拖曳調(diào)換順序 適用gis中切換圖層順序--> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body{ display: flex; padding: 100px; flex-direction: column; } div{ width: 100px; height: 100px; text-align: center; } </style> </head> <body> <div draggable="true">紅色</div> <div draggable="true">綠色</div> <div draggable="true">藍(lán)色</div> </body> <script type="text/javascript"> let div =document.getElementsByTagName("div"); let container=null; // 遍歷給每一個(gè)div綁定 dragstart dragover以及drop事件 for(let i=0;i<div.length;i++){ div[i].ondragstart=function(){ container=this } div[i].ondragover=function(){ event.preventDefault(); } div[i].ondrop=function(){ debugger; if(container!=null&&container!=this){ // 具體思路跟變量值互換一樣 let temp=document.createElement("div"); document.body.replaceChild(temp,this); //用新建的div占據(jù)目的位置 document.body.replaceChild(this,container);// 目的div放置在起始位置 document.body.replaceChild(container,temp) // 起始div放置在目的位置 debugger; console.log('執(zhí)行業(yè)務(wù)邏輯') } } } </script> </html>
感謝各位的閱讀!關(guān)于“javascript如何實(shí)現(xiàn)拖曳互換div的位置”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(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)容。