原生JS实现鼠标按下拖拽效果
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>鼠标拖动title>
<style type="text/css">
body {
margin: 0;
}
div {
width: 200px;
height: 200px;
position: absolute;
background-color: pink;
}
style>
head>
<body>
<div onmousedown="downDiv(this)" onmousemove="moveDiv(this)" onmouseup="upDiv(this)">
div>
<script>
var obj_w, obj_h;
var mouseDown = false;
function downDiv(obj) {
obj_w = obj.offsetWidth;
obj_h = obj.offsetHeight;
var e = event || window.event;
obj.style.left = (e.clientX - obj_w / 2) + "px";
obj.style.top = (e.clientY - obj_h / 2) + "px";
console.log(obj.style.left, obj.style.top)
mouseDown = true;
}
function moveDiv(obj) {
obj_w = obj.offsetWidth;
obj_h = obj.offsetHeight;
var e = event || window.event;
console.log(e.clientX, e.clientY);
console.log(obj_w, obj_h);
if (mouseDown) {
obj.style.left = (e.clientX - obj_w / 2) + "px";
obj.style.top = (e.clientY - obj_h / 2) + "px";
console.log(obj.style.left, obj.style.top)
}
}
function upDiv(obj) {
mouseDown = false;
}
script>
body>
html>