首先要給要拖拽的元素增加draggable屬性龟劲,然后就可以注冊(cè)以下事件了。
Event | On Event Handler | Fires when… |
---|---|---|
drag |
ondrag |
…a dragged item (element or text selection) is dragged. |
dragend |
ondragend |
…a drag operation ends (such as releasing a mouse button or hitting the Esc key; see Finishing a Drag.) |
dragenter |
ondragenter |
…a dragged item enters a valid drop target. (See Specifying Drop Targets.) |
dragexit |
ondragexit |
…an element is no longer the drag operation's immediate selection target. |
dragleave |
ondragleave |
…a dragged item leaves a valid drop target. |
dragover |
ondragover |
…a dragged item is being dragged over a valid drop target, every few hundred milliseconds. |
dragstart |
ondragstart |
…the user starts dragging an item. (See Starting a Drag Operation.) |
drop |
ondrop |
…an item is dropped on a valid drop target. (See Performing a Drop.) |
簡(jiǎn)單的demo如下:
<!--
* @Author: sunxy
* @Date: 2021-06-27 13:42:03
* @LastEditors: sunxy
* @LastEditTime: 2021-06-27 17:51:00
* @Description: 拖拽功能
* @FilePath: /feir/cli/src/draggable.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.empty {
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div> 拖拽到下面的盒子</div>
<div class="empty"></div>
<img draggable="true" src="./images/img.png" />
</body>
<script>
// drag event
/**
* 開始 dragstart 進(jìn)入時(shí) dragenter
* 進(jìn)行中 drag 進(jìn)入后 dragover
* 結(jié)束 dragend 離開 dragover 放置 drop
*/
const empty = document.querySelector('div.empty')
document.addEventListener('dragstart', e => {
// 開始拖動(dòng)的時(shí)候給添加紅色邊框
e.target.style.border = '1px dashed red'
}, false)
document.addEventListener('dragend', e => {
// 結(jié)束拖動(dòng)的時(shí)候 取消邊框
e.target.style.border = 'none'
}, false)
empty.addEventListener('dragenter', e => {
e.preventDefault()
e.target.style.border = '1px dashed green'
// 進(jìn)入的時(shí)候 添加元素
e.target.appendChild(document.querySelector('img'))
}, false)
</script>
</html>