今天介绍一下原生javascript拖拽事件。
很重要的一点,如果想要一个元素允许被拖动,必须给该元素加上draggable=true,该默认值为false。
h5拖拽事件分为两种:
被拖拽事件
- ondragestart 被拖拽开始事件
- ondrag 拖拽进行中事件
- ondragend 被拖拽元素结束事件
目标元素事件
- ondragenter 被拖拽元素进入目标元素事件(基于鼠标位置看是否进入目标元素范围)
- ondragover 被拖拽元素在目标元素上移动
- ondragleave 被拖拽元素离开目标元素事件
- ondrop 被拖拽元素在目标元素范围上释放
拖拽事件需要阻止浏览器默认事件,否则目标元素事件第 4 点用户看不到效果
浏览器的默认事件 浏览器就是事件对象event
UI布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽上传</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: #00f;
cursor: pointer;
}
.tuozhuai{
width: 500px;
height: 500px;
border: 1px solid #f00;
margin-top: 200px;
margin-left: 600px;
}
</style>
</head>
<body>
<!-- 如果一个元素想要允许被拖拽,必须加draggable属性为true,默认是false -->
<div class="box" draggable="true"></div>
<div class="tuozhuai">拖拽到此区域</div>
</body>
</html>
js代码实现:
1. 被拖拽元素事件
<script>
var box = document.querySelector('.box');
box.ondragstart=function(){
this.style.background = 'green';
}
box.ondrag=function(){
this.innerHTML='被拖拽中...';
}
box.ondragend = function(){
this.innerHTML='';
this.style.background = '#00f';
}
</script>
2.目标元素事件
<script>
var tuozhuai = document.querySelector('.tuozhuai');
被拖拽元素进入目标元素事件
// 该事件会被over事件覆盖,因为一旦进入拖拽区域,就是再移动了。所以该事件用户看不见,
// 但确实发生了(例如:起步,跑,他俩也是同时发生的,但是看不到起步的动作)
tuozhuai.ondragenter = function(e){
e.preventDefault(); //阻止浏览器默认动作
this.innerHTML='进入目标元素';
this.style.background = '#fcc';
}
被拖拽元素在目标元素上移动
tuozhuai.ondragover = function(e){
e.preventDefault(); //阻止浏览器默认动作
this.innerHTML='在目标元素上移动';
this.style.background = '#cfc';
}
被拖拽元素离开目标元素事件
tuozhuai.ondragleave = function () {
this.innerHTML = '离开目标元素';
this.style.background = 'none';
}
被拖拽元素在目标元素范围上释放
// 该事件会被浏览器默认事件阻止,所以要阻止掉浏览器的默认事件
// (阻止浏览器默认事件要从最初第一个事件(ondragenter)开始
// 到第二个(ondragover)结束时该事件就不会被阻止了)
tuozhuai.ondrop = function(){
this.innerHTML = '在目标元素上松开被拖拽元素';
this,style.background = 'none';
}
</script>