HTML部分
<div id="container" > <div id="drag"> 拖拽区域 </div> </div>
CSS部分:
#container { width: 300px; /* overflow: hidden有效阻止鼠标超出拖动范围而触发mousemove回调 */ overflow: hidden; position: relative; height: 300px; background-color: #ddd } #drag { color: white; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; font-size: 12px; position: absolute; user-select: none; cursor: pointer; background-color: rgb(0, 174, 255); }
JavaScript部分:
let container = document.getElementById('container') let drag = document.getElementById('drag') drag.style.left = "0px" drag.style.top = "0" drag.onmousedown = function (event) { let clientX = parseInt(event.clientX)//鼠标事件的x坐标位置 let clientY = parseInt(event.clientY)//鼠标事件的y坐标位置 let currentLeft = parseInt(drag.style.left) let currentTop = parseInt(drag.style.top) container.onmousemove = function (event) { drag.style.left = (event.clientX - clientX + currentLeft) + "px" drag.style.top = (event.clientY - clientY + currentTop) + "px" } //监听整个文档区域,避免拖拽到边缘鼠标放开没有监听到回调 document.onmouseup = function () { container.onmousemove = null } }
效果
标签:clientX,style,container,效果,拖拽,drag,let,JS,event From: https://www.cnblogs.com/mesmerize/p/16649499.html