react 移动端盒子拖拽
html结构
<div className='content' ref={boxs} > { lists.map((item, index) => { return ( <span key={index} className='box' style={{ backgroundImage: `url(${item.img})`, top: item.top, left: item.left }} > {item.title} <div className='close' onClick={(e) => delCard(e, index)}></div> </span> ) }) } </div>
盒子的基本样式
.movecard>.content { border: 1px solid black; height: 400px; position: relative; padding: 20px; box-sizing: border-box; } .movecard>.content>.box { border: 1px solid black; position: absolute; border-radius: 3px; height: 60px; width: 60px; cursor: move; background-size: cover; background-repeat: no-repeat; color:white; box-sizing: border-box; padding-top: 10px; } .movecard>.content>.box .close{ position: absolute; top: 0; right: 0; text-align: center; line-height: 15px; border-radius: 50%; height: 15px; width: 15px; position: absolute; background-color:white; color: red; } .movecard>.imgs { display: flex; justify-content: space-evenly; margin: 20px 0; } .movecard>.imgs img { border-radius: 3px; height: 60px; width: 60px; } .imgOn{ border-radius: 3px; height: 60px; width: 60px; border: 3px solid rgb(98, 255, 98); box-sizing: border-box; }
拖拽的方法
// 设置心愿卡片的拖动监听事件 useEffect(() => { // 第一步:给元素添加开始触摸事件,获取元素原本对于浏览器的x,y位置 boxs.current.addEventListener('touchstart', (e) => { if (e.target.nodeName !== 'SPAN') return; let X = e.touches[0].clientX; let Y = e.touches[0].clientY; let boxX = e.target.offsetLeft; let boxY = e.target.offsetTop; // 第二步:设置元素拖动事件,拖动时获取元素对于窗口的位置, // 使用这个位置-开始点击时对于窗口的位置+元素当前对于父盒子定位的偏移值 // 就可以实时得到当前的偏移值,实时赋值给元素的top、left属性 e.target.addEventListener('touchmove', (e) => { let { clientX, clientY } = e.touches[0]; let moveX = clientX - X + boxX <= 0 ? 0 : clientX - X + boxX; let moveY = clientY - Y + boxY <= 0 ? 0 : clientY - Y + boxY; e.target.style.left = moveX + 'px'; e.target.style.top = moveY + 'px'; // 第三步:最后加个拖动的范围就可 if (moveX >= 345 - e.target.clientWidth) { e.target.style.left = 345 - e.target.clientWidth + 'px'; } if (moveY >= 395 - e.target.clientHeight) { e.target.style.top = 395 - e.target.clientHeight + 'px'; } }) }) }, [])