这两天需要用到drag,又回头把知识捡了起来,这里简单的记录一下
页面布局与样式
基本样式如下,除了要设置draggable="true"
没什么需要注意的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
<style>
main{
width: 100vw;
height: 100vh;
background-color: #000;
display: flex;
justify-content: space-around;
align-items: center;
}
.contain{
width: 200px;
height: 200px;
}
.dragable,.dropable{
border-radius: 10px;
width: 200px;
height: 200px;
}
.dragable{
background-color: rgb(0, 159, 233);
}
.dropable{
border: 2px dashed rgb(0, 159, 233);
position: relative;
}
.dropable::before{
content: '请将元素拖拽至此';
position: absolute;
color: blanchedalmond;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100%;
text-align: center;
}
.dragOver{
border: 2px dashed orange;
}
.draged{
border: 2px dashed greenyellow;
}
.draged img{
width: 80%;
}
</style>
</head>
<body>
<main>
<div class="contain">
<div id="sixsixsix" class="dragable" draggable="true"></div>
</div>
<div class="dropable"></div>
</main>
</body>
</html>
逻辑
分别用
dragstart
,dragover
,dragleave
监测开始拖拽、拖拽至上面时、拖拽离开时
drop
用于将元素拖拽到指定区域松开鼠标后的操作
let dragable = document.querySelector('.dragable');
let dropable = document.querySelector('.dropable');
// 拖拽开始时将id存放至dataTransfer的字段中
dragable.addEventListener('dragstart',(e)=>{
e.dataTransfer.setData('drag',e.target.id);
})
// 拖拽至虚框上时
dropable.addEventListener('dragover',(e)=>{
e.preventDefault();
dropable.classList.add('draged');
})
// 离开虚框时
dropable.addEventListener('dragleave',(e)=>{
dropable.classList.remove('draged');
})
// 完成拖拽松开鼠标
dropable.addEventListener('drop',(e)=>{
e.preventDefault();
let drag = e.dataTransfer.getData('drag');
dropable.appendChild(document.getElementById(drag));
dropable.classList.add('.draged');
})
拖拽图片
let dropable = document.querySelector('.dropable');
// 拖拽至虚框上时
dropable.addEventListener('dragover',(e)=>{
e.preventDefault();
dropable.classList.add('draged');
})
// 离开虚框时
dropable.addEventListener('dragleave',(e)=>{
dropable.classList.remove('draged');
})
// 完成拖拽松开鼠标
dropable.addEventListener('drop',(e)=>{
e.preventDefault();
if(e.dataTransfer.items[0].kind === 'file'){
const file = e.dataTransfer.items[0].getAsFile();
if(!file.type.startsWith('image/')){
return
}
const image = document.createElement('img');
image.src = URL.createObjectURL(file);
image.onload = function(){
URL.revokeObjectURL(this.src)
}
dropable.appendChild(image)
}
})