拖拽功能是我們?nèi)粘m?xiàng)目中常用的效果,今天我們就來研究一下如何實(shí)現(xiàn)簡單的拖拽功能臂聋。
想實(shí)現(xiàn)拖拽功能其實(shí)很簡單光稼,主要需要三個(gè)事件:
1、mousedown:鼠標(biāo)按下
2孩等、mousemove:鼠標(biāo)移動(dòng)
3艾君、mouseup:鼠標(biāo)抬起
思路很簡單,鼠標(biāo)按下的時(shí)候肄方,記錄下鼠標(biāo)按下時(shí)的x,y冰垄,即e.clientX和e.clientY,還有記錄下當(dāng)前div的坐標(biāo)位置即div.offsetLeft及div.offsetTop权她。當(dāng)鼠標(biāo)移動(dòng)時(shí)虹茶,再次記錄下鼠標(biāo)當(dāng)前的x,y逝薪,
此時(shí)div坐標(biāo)分別為:
x=現(xiàn)在的鼠標(biāo)位置x-開始按下的鼠標(biāo)位置x+div的原始坐標(biāo)x
y=現(xiàn)在的鼠標(biāo)位置y-開始按下的鼠標(biāo)位置y+div的原始坐標(biāo)y
最后當(dāng)鼠標(biāo)抬起時(shí),解綁蝴罪。
下面上代碼:
function drag(el){
el.addEventListener('mousedown',function(e){
let start = {
x:e.clientX,
y:e.clientY
}
let startPos = {
x:css(el,'left'),
y:css(el,'top')
}
function move(e){
let dis = {
x:e.clientX-start.x,
y:e.clientY-start.y
}
let x = dis.x+startPos.x;
let y = dis.y+startPos.y;
//邊界處理董济,取大小值
x= Math.max(0,x);
x = Math.min(x,document.documentElement.clientWidth-box.clientWidth);
y = Math.max(0,y);
y = Math.min(y,document.documentElement.clientHeight-box.clientHeight);
el.style.left = x+'px';
el.style.top = y+'px';
e.preventDefault();
}
document.addEventListener('mousemove',move);
document.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',move);
},{
once:true
});
})
}
是不是很簡單啊,下面擴(kuò)展一下碰撞檢測的方法:
function isContact(el1,el2){
//獲取四條邊的位置
let el1Pos = el1.getBoundingClientRect();
let el2Pos = el2.getBoundingClientRect();
if(//碰上
el1Pos.right>el2Pos.left&&
el1Pos.left<el2Pos.right&&
el1Pos.bottom>el2Pos.top&&
el1Pos.top<el2Pos.bottom
){
return true;
}else{
return false;
}
}
這里很好理解洲炊,簡單解釋一下getBoundingClientRect():
該方法是返回元素的大小及其相對(duì)于視口的位置感局,包含四個(gè)只讀屬性:left、right暂衡、top询微、bottom。
詳細(xì)可以參考MDN上對(duì)該方法的介紹:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect