<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<script>
var div_ = document.querySelector('div');
//鼠标按下事件 获取x y 距离
div_.onmousedown = function (e) {
e = e || window.event;
// x y 的值为鼠标点击的位置距离点击的元素的距离
var x = e.offsetX;
var y = e.offsetY;
//鼠标移动事件 获取移动时距离浏览器页面的距离
//因为这个事件发生在整个文档中,所以要给这个文档添加移动事件
var flag = true;
document.onmousemove = function (e) {
e = e || window.event;
//距离浏览器的距离-距离元素距离=实际移动距离
div_.style.left = e.clientX - x + 'px';
div_.style.top = e.clientY - y + 'px';
// 节流
// if (flag) {
// flag = false;
// e = e || window.event;
// div_.style.left = e.clientX - x + 'px';
// div_.style.top = e.clientY - y + 'px';
// setTimeout(() => {
// flag = true;
// }, 100);
// }
}
}
//当鼠标抬起时将鼠标事件清除
div_.onmouseup = function () {
document.onmousemove = null;
}
</script>
拖拽小案例
最新推荐文章于 2024-07-28 20:27:10 发布