Javascript方法实现拖曳和用HTML实现拖曳
1.js实现拖曳
<!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: pink;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
let box = document.querySelector('#box');
//鼠标按下
box.onmousedown = function (e) {
//鼠标按下的位置
let x = e.x - parseInt(box.style.left || 0);
let y = e.y - parseInt(box.style.top || 0);
//鼠标移动
document.onmousemove = function (e) {
//鼠标移动的距离减去按下的位置
let left = e.x - x;
let top = e.y - y;
box.style.left = left + "px";
box.style.top = top + "px";
console.log(e.x, e.y);
}
//鼠标离开
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
</html>
2.html实现拖曳
<!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: aquamarine;
position: absolute;
left: 0;
top: 0;
}
html,body{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="box" draggable="true"></div>
<script>
let box = document.querySelector(".box");
let x=0;
let y=0;
//ondragstart:开始移动
box.ondragstart = function(e){
x = e.x - parseInt(box.style.left || 0);
y = e.y - parseInt(box.style.top || 0);
console.log(e.x);
console.log(x,y);
}
//想要是drop实现效果,必须将投放在对象上的dragover事件的默认行为阻止才能起作用
document.body.ondragover = function(e){
e.preventDefault();
}
//落下
//只可视页面移动:document.body.ondrop = function (e)
//滚动页面也可移动:box.ondragend = function (e)
box.ondragend = function (e) {
console.log("drop");
let left = e.x - x;
let top = e.y - y;
box.style.left = left + "px";
box.style.top = top + "px";
console.log(box.style.left, box.style.top);
}
</script>
</body>
</html>