原生JS實現可橫向拖拽div方法

2021-10-01 03:55:43 字數 1722 閱讀 2754

function dragdiv(doucument,classname)

function dodown()

//構建乙個被操作的元素物件

theobject = new resizeobject();

theobject.el = el;

theobject.grabx = window.event.clientx;

theobject.graby = window.event.clienty;

theobject.width = el.offsetwidth;

theobject.left = el.offsetleft;

window.event.returnvalue = false;//取消事件處理程式中呼叫函式的預設操作

window.event.cancelbubble = true;//取消冒泡

}//把操作的元素置為空

function doup() }//

function domove()

//開始拖拉的位置

if(theobject != null)

}//判斷當前的元素是否合格(不為空,不能為body)

//判斷當前元素的css類名是否為指定類名

function getreal(el, type, value)

temp = temp.parentelement;

} return el;

}document.onmousedown = dodown;

document.onmouseup = doup;

document.onmousemove = domove;

}

上面部分是es5的寫法,es6的寫法如下所示:

class changevm 

setup()

dodown()

this.eldoc = el.parentnode

this.grabx = window.event.clientx

this.graby = window.event.clienty

this.width = this.eldoc.offsetwidth

this.left = this.eldoc.offsetleft

if(!this.oridocwidth)

window.event.returnvalue = false

window.event.cancelbubble = true

}doup()

}domove()

const xmax = (this.width + window.event.clientx) - this.grabx

const tempwidth = math.max(xmin, xmax)

this.eldoc.style.width = `$px`

this.elvm.style.width=this.orivmwidth+this.oridocwidth-tempwidth+'px'

window.event.returnvalue = false

window.event.cancelbubble = true}}

}const changevm = new changevm

changevm.setup()

相對而言,es6的寫法更加清晰,易讀。有收穫的小夥伴別忘記點讚哦!

js實現可拖拽的div

doctype html html lang en head meta charset utf 8 title zzw drap title style box bar content style head body div id box div id bar 可拖拽頭部 div div id co...

原生js實現拖拽盒子

盒子必須是絕對定位的盒子 滑鼠在盒子內部按下時獲得相對座標。事件物件在頁面的位置減去盒子距離body的距離 滑鼠移動時,使得盒子的位置發生變化 滑鼠鬆開時,不再拖動 移動事件失效 lang zh charset utf 8 name viewport content width device wid...

原生js使用drag實現拖拽排序

先介紹一下html5的drag屬性,拖放 drag 和 drop 是 html5 標準的組成部分。想要啟用drag,只要給元素加上draggable true 就行了 safari 5.1.2除外 實際效果 拖動事件 了解事件詳情 事件分為兩類,當前拖動的元素上的事件,以及要放置的位置接收到的事件。...