自鼠标被发明以来,拖曳操作在计算机的操作中无处不在。例如,移动文件、图片处理等都需要拖曳。但是如此常见的操作,在Web世界只能通过模拟方式来实现。
在HTML5的规范中,可以通过为元素增加draggable= "true"来设置此元素是否可以进行拖曳操作,很大程度上简化了拖曳交互的难度。其中图片、链接默认是开启的。
在HTML5的拖曳操作中,首先要明确拖曳元素和目标元素。
(1)拖曳元素:即页面中设置了draggable=“rue” 属性的元素。
(2)目标元素:页面中任何一个元素都可以成为目标元素。
在HTML5中提供了关于拖曳元素和目标元素的事件监听,如表所示。
表1 应用于拖曳元素的事件监听
方法 | 描述 |
---|---|
ondrag() | 整个拖曳过程都会调用 |
– | – |
ondragstart() | 当拖曳开始时调用 |
– | – |
ondragleave() | 当鼠标离开拖曳元素时调用 |
– | – |
ondragend() | 当拖曳结束时调用 |
表2 应用于目标元素的事件监听
方法 | 描述 |
---|---|
Ondragenter | 当拖曳元素进入时调用 |
– | – |
ondragover | 当停留在目标元素上时调用 |
– | – |
ondrop | 当在目标元素上松开鼠标时调用 |
– | – |
ondragleave | 当鼠标离开目标元素时调用 |
– | – |
下面通过一个案例来演示HTML5中的拖曳操作,代码如示例所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖曳</title>
<style>
body {
padding: 0;
margin: 0;
background-color: #F7F7F7;
position: relative;
}
.box {
width: 150px;
height: 150px;
background-color: yellow;
position: absolute;
top: 100px;
left: 50px;
}
.container {
width: 300px;
height: 300px;
background-color: green;
position: absolute;
top: 100px;
left: 50%;
margin-left: -150px;
}
</style>
</head>
<body>
<div class="box" draggable="true"></div>
<div class="container"></div>
<script>
var box = document.querySelector('.box');
var container = document.querySelector('.container');
// 整个拖拽都会执行
box.addEventListener('drag', function () {
console.log(1);
});
box.addEventListener('dragleave', function () {
console.log(2);
});
// 拖拽开始
box.addEventListener('dragstart', function () {
this.style.backgroundColor = 'pink';
console.log(3)
});
// 拖拽结束
box.addEventListener('dragend', function (ev) {
this.style.backgroundColor = '';
// console.log(ev);
});
// 进入到目标
container.addEventListener('dragenter', function () {
this.style.backgroundColor = 'pink';
});
// 在目标元素上移动
container.addEventListener('dragover', function (ev) {
this.style.backgroundColor = 'yellow';
ev.preventDefault();
});
//
container.addEventListener('drop', function (ev) {
this.style.backgroundColor = 'black';
console.log(ev);
ev.preventDefault();
});
</script>
</body>
</html>
在上述代码中,首先准备两个盒子:box为拖曳元素,container为目标元素。
用Chrome浏览器访问示例,并按[F12] 键打开浏览器的控制台。
在示例中,设置了从拖曳开始、移动、进入目标的一系列监听,读者可以根据控制台打印的数据来感受监听过程。因为在书本中无法打印出颜色的变化,这里就不做过多的说明,该案例要求读者仔细在计算机上实践观察。