应用:
1.拖拽排序
2.拖拽上传
3.拖拽裁剪
拖拽流程
确定可拖拽的内容-->开始拖拽-->拖拽过程-->结束拖拽
draggable dragstart drag(dragenter\dragleave\dragover) drag(dragend)
拖拽知识点
·draggable 状态:true\false\auto(默认值)
默认能被拖拽:
-<img>
-表示图片的<object>
-<a>
-选中的文本
<ol>
<li draggable="true">Apple</li>
<li draggable="true">Pear</li>
<li draggable="true">Orange</li>
</ol>
DragEvent
-dataTransfer.dropEffect(none\move\copy\link):
表示拖拽的内容当前位置可被放置的效果;
在dragstart\drag\dragexit\dragleave事件中值为none;
在drop,dragend事件中对应当前的dropEffect;
在其他事件如dragenter\dragover取决于effectAllowed
-dataTransfer.effectAllowed(none\copy\copyLink\copyMove\link\linkMove\move\all\uninitialized):
表示拖拽的内容被允许的操作效果;
只能在dragstart事件中设置
用于dragenter和dragover事件中初始化dropEffect
-dataTransfer.setDragImage(element,x,y):
只能在dragstart事件中设置
拖拽数据操作
-dataTransfer.types
-dataTransfer.items
-dataTransfer.files
-dataTransfer.setData(format,data)
-dataTransfer.getData(format)
-dataTransfer.clearData([format])
案例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>which fruit do you like</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)" style="background-color: rgb(255, 255, 240);border: 1px solid #bbb;">
<li draggable="true" data-value="Apples">Apples</li>
<li draggable="true" data-value="Oranges">Oranges</li>
<li draggable="true" data-value="Pears">Pears</li>
</ol>
<p>Drop your favorite fruits belows:</p>
<ol ondrop="dropHandler(event)" ondragover="dragOverHandler(event)" style="background-color: rgb(255, 255, 240);border: 1px solid #bbb;height: 100px;">
</ol>
<script type="text/javascript">
let imgs = {
Apples: getImage('./apple.jpg'),
Oranges:getImage('./orange.jpg'),
Pears:getImage('./pear.jpg')
};
function getImage(src) {
let img = new Image();
img.src = src;
return img;
}
function dragStartHandler(event) {
if (event.target instanceof HTMLLIElement) {
let value = event.target.dataset.value;
event.dataTransfer.setData(
'text/fruit',value
);
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setDragImage(imgs[value],25,0);
} else {
event.preventDefault();
}
}
function dragOverHandler(event) {
event.preventDefault();
}//拖拽过程需要去掉默认的,要不只能对textarea input输入框产生效果
function dragEndHandler(event) {
if (event.dataTransfer.dropEffect === 'move') {
event.target.parentNode.removeChild(event.target);
}
}
function dropHandler(event) {
let li = document.createElement('li');
li.textContent = event.dataTransfer.getData('text/fruit');
event.target.appendChild(li);
}
</script>
</body>
</html>
兼容性
MouseEvent模拟
网友评论