项目中经常遇到这种需求,特此记录下:
css部分:
<style> #target { width: 200px; height: 200px; border-radius: 6px; background: #eee; position: absolute; } </style>
html部分:
<div id="target"></div>
js部分(这里分了两种情况,因为pc端与移动端的处理情况有点不太一样):
(1)、pc端
const winW = window.innerWidth const winH = window.innerHeight const target = document.getElementById(‘target‘) const targetW = target.offsetWidth const targetH = target.offsetHeight const maxL = winW - targetW // 距离左侧的最大距离 const maxT = winH - targetH // 距离顶部的最大距离 let posArr = [] target.addEventListener(‘mousedown‘, function (e) { posArr = [e.clientX, e.clientY] }) document.addEventListener(‘mousemove‘, function (e) { let [x, y] = [e.clientX, e.clientY] const deltaX = x - posArr[0] // 移动的水平距离 const deltaY = y - posArr[1] // 移动的垂直距离 const left = parseInt(target.style.left || 0) // 如果值不存在时,赋默认值很关键,不然值为NaN const top = parseInt(target.style.top || 0) let [moveX, moveY] = [‘‘, ‘‘] if (left + deltaX > maxL) { moveX = maxL } else if (left + deltaX >= 0 && left + deltaX <= maxL) { moveX = left + deltaX } else { moveX = 0 } if (top + deltaY > maxT) { moveY = maxT } else if (top + deltaY >= 0 && top + deltaY <= maxT) { moveY = top + deltaY } else { moveY = 0 } target.style.left = moveX + ‘px‘ target.style.top = moveY + ‘px‘ posArr = [x, y] })
(2)、移动端,情况稍微有点不一样,监听的事件为touch事件,其次获取元素当前位置也有点不一样,具体代码:
const winW = window.innerWidth const winH = window.innerHeight const target = document.getElementById(‘target‘) const targetW = target.offsetWidth const targetH = target.offsetHeight const maxL = winW - targetW // 距离左侧的最大距离 const maxT = winH - targetH // 距离顶部的最大距离 let posArr = [] target.addEventListener(‘touchstart‘, function (e) { posArr = [e.changedTouches[0].clientX, e.changedTouches[0].clientY] }) document.addEventListener(‘touchmove‘, function (e) { let [x, y] = [e.changedTouches[0].clientX, e.changedTouches[0].clientY] const deltaX = x - posArr[0] // 移动的水平距离 const deltaY = y - posArr[1] // 移动的垂直距离 const left = parseInt(target.style.left || 0) // 如果值不存在时,赋默认值很关键,不然值为NaN const top = parseInt(target.style.top || 0) let [moveX, moveY] = [‘‘, ‘‘] if (left + deltaX > maxL) { moveX = maxL } else if (left + deltaX >= 0 && left + deltaX <= maxL) { moveX = left + deltaX } else { moveX = 0 } if (top + deltaY > maxT) { moveY = maxT } else if (top + deltaY >= 0 && top + deltaY <= maxT) { moveY = top + deltaY } else { moveY = 0 } target.style.left = moveX + ‘px‘ target.style.top = moveY + ‘px‘ posArr = [x, y] })