1.es6 class的使用
之前在Jquery时代,实现拖拽功能都是使用函数直接搞,有了es6中的class,可以很好的封装相关的功能,只要给个ID就可以,想拖谁就拖谁!不过步骤还是老一套。
- 先在拖拽元素DOM上添加onmousedown事件,获取鼠标点击位置,并添加document的onmousemove事件和onmouseup事件
- 只要鼠标不弹起,就会执行onmousemove事件,然后事件中给拖拽元素top,left赋值,不想让他出去可以,限制范围
- 鼠标弹起时,移除事件
js真是有点Java的样子啦!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script type="text/javascript">
class Drag {
constructor(id) {
this.oDiv = document.