一、创建一个想要拖动的盒子
<div id="drag-button">
<!-- <button>可拖动按钮</button> -->
<van-icon name="apps-o" size="30" class="button"></van-icon>
</div>
二、js
mounted() {
// 可拖动的按钮
const dragButton = document.getElementById('drag-button');
const button = dragButton.querySelector('.button');
let isDragging = false;
let initialX = 0;
let initialY = 0;
let currentX = 0;
let currentY = 0;
button.addEventListener('touchstart', (event) => {
isDragging = true;
initialX = event.touches[0].clientX - currentX;
initialY = event.touches[0].clientY - currentY;
});
button.addEventListener('touchmove', (event) => {
if (isDragging) {
event.preventDefault();
currentX = event.touches[0].clientX - initialX;
currentY = event.touches[0].clientY - initialY;
button.style.transform = `translate(${currentX}px, ${currentY}px)`;
}
});
button.addEventListener('touchend', () => {
isDragging = false;
});
}
三、调整 css 样式
#drag-button {
position: absolute;
top: 80%;
right: 40px;
transform: translate(-50%, -50%);
z-index: 9999;
}
#drag-button .button {
background: pink;
border-radius: 50%;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
color: #fff;
border: none;
border-radius: 5px;
}