准备一个方块:
<style>.drag{background-color:#aaf;position:absolute;}
</style>
<div class="drag" style="width:100px;height:100px;top:0;left:0"></div>
监听鼠标的按住事件:
let dragDiv = document.getElementsByClassName("drag")[0];
let mousedown = (event)=>{alert("按住了");
}dragDiv.addEventListener("mousedown", mousedown,false);
按住事件(具体):
// 首先鼠标得变成一个pointer状态,
// 然后监听移动事件,让方块跟着鼠标动(style.left = 鼠标距离左侧得距离(event.clientX) - 鼠标与方块左边距的距离(dragDiv.style.left))
// 重写mousedown.
let mousedown = (event) => {let relaLeft = event.clientX- parseInt(dragDiv.style.left);let relaTop = event.clientY- parseInt(dragDiv.style.top);// 点击时候的样式dragDiv.style.cursor = "pointer";dragDiv.style.border = "1px solid red";// 监听鼠标移动 (注意是监听document)document.onmousemove = (event) => {// 小方格跟着鼠标移动dragDiv.style.left = event.clientX - relaLeft + 'px' ;dragDiv.style.top = event.clientY - relaTop + 'px' ;// 小方格的边界if( parseInt(dragDiv.style.left) <=0) {dragDiv.style.left = 0}if( parseInt(dragDiv.style.top) <= 0 ){ dragDiv.style.top = 0}if( parseInt(dragDiv.style.left) >= window.innerWidth - parseInt(dragDiv.style.width)) {dragDiv.style.left = window.innerWidth - parseInt(dragDiv.style.width) + 'px';}if( parseInt(dragDiv.style.top) >= window.innerHeight - parseInt(dragDiv.style.height)) {dragDiv.style.top = window.innerHeight - parseInt(dragDiv.style.height) + 'px';}}document.onmouseup = () => {dragDiv.style.border = "";document.onmouseup = null;document.onmousemove = null;}
}
参考 原生js实现拖拽功能