<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>drag</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div draggable="true"></div>
<script type="text/javascript">
var dragDiv = document.querySelector('div');
dragDiv.ondragstart = function() {
console.log('被抓住 开始移动的一瞬间')
// 按下鼠标并开始移动鼠标,会在被拖动元素上触发 dragstart 事件
}
dragDiv.ondrag = function() {
this.innerHTML += '抓不到....';
this.style.backgroundColor = 'green';
// 在触发 dragstart 事件 后, 随机会触发 drag 事件,元素被拖动期间,事件会被持续触发
}
dragDiv.ondragend = function() {
this.innerHTML = ''
this.style.backgroundColor = 'orange'
// 拖动结束 也就是鼠标松开会触发的事件
}
</script>
</body>
</html>
上述运行结果: