拖拽
实现工具
mousedown-----某个鼠标按键被按下
mousemove-----鼠标被移动
mouseup-----某个鼠标按键被松开
event.clientX-----事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平坐标。客户区指的是当前窗口。
offsetLeft-------获取对象相对于版面或由offsetParent属性指定的父坐标的左侧位置。
style.top----给物体定位,拖拽后物体的绝对位置。
document.documentElement.clientWidth----获取当前页面宽度
基本思路
第一步:记录鼠标按下位置和被拖拽物体的相对距离
实现事件:mousedown
实现代码:var offsetX = e.clientX - node.offsetLeft;//水平方向的相对位置
实现代码:var offsetY = e.clientY - node.offsetTop;//垂直方向的相对位置
第二步:一直保持,相对距离,计算移动后的物体绝对距离
实现事件:mousemove
实现代码:style.left = e.clientX - offsetX + 'px';//注意后面的px不能漏掉
实现代码:style.top = e.clientY - offsetY + 'px';
第三步:防止物体被移除窗口,增加限定条件
var w = e.clientX - offsetX;
var h = e.clientY - offsetY;
//限制出界
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
if (w <= 0) {
w = 0;
}
if (w >= windowWidth - event.offsetWidth) {
w = windowWidth - event.offsetWidth;
}
if (h <= 0) {
h = 0;
}
if (h >= windowHeight - event.offsetHeight) {
h = windowHeight - event.offsetHeight
}
第四步:取消拖拽事件。
原理图
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#div1 {
width: 100px;
height: 100px;
background-color: rgb(0, 119, 255);
position: absolute;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById("div1");
drag(oDiv)
}
function drag(event) {
event.onmousedown = function (ev) {
var e = ev || window.event; //拿到当前鼠标的事件对象
var offsetX = e.clientX - this.offsetLeft;
var offsetY = e.clientY - this.offsetTop;
document.onmousemove = function (ev) { //注意这里是鼠标拖着整个div在移动事件应该添加在整个document
var e = ev || window.event; //拿到当前鼠标的事件对象
var w = e.clientX - offsetX;
var h = e.clientY - offsetY;
//限制出界
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
if (w <= 0) {
w = 0;
}
if (w >= windowWidth - event.offsetWidth) {
w = windowWidth - event.offsetWidth;
}
if (h <= 0) {
h = 0;
}
if (h >= windowHeight - event.offsetHeight) {
h = windowHeight - event.offsetHeight
}
event.style.left = w + 'px';
event.style.top = h + 'px';
}
}
document.onmouseup = function (ev) {
document.onmousemove = null;
}
}
</script>
<body>
<div id="div1"></div>
</body>
</html>