再添加盒子的父级盒子设置相对定位,创建的box设置绝对定位
let box = document.createElement('div') // 创建盒子
box.className = 'home-box' // 添加类名
box.innerText = content // 设置盒子内容
box.style.left = Math.random() * 100 + 'px' // 随机设置盒子的left值
box.style.top = Math.random() * 100 + 'px' // 随机设置盒子的top值
document.querySelector('.home-con').appendChild(box) // 将盒子添加到home-con区域内
var startX=0
var startY=0
box.addEventListener('touchstart', function(e) { // 监听鼠标按下事件
let touch = null
if (e.touches) {
touch = e.touches[0];
} else {
touch = e
}
setTimeout(()=>{
setIsDragging(true) // 设置正在拖拽
},500)
setIsDragging(true)
startX = touch.pageX - box.offsetLeft
startY = touch.pageY - box.offsetTop
})
box.addEventListener('touchend', () => { // 监听鼠标松开事件
console.log('松开');
setIsDragging(false) // 设置拖拽结束
})
box.addEventListener('touchmove', function(e){ // 监听鼠标移动事件
let touch = null
if (e.touches) {
touch = e.touches[0];
} else {
touch = e
}
if (touch.pageX - startX<= 0) {//限制左边
box.style.left = 0 + "px"
return false
}
if (touch.pageX - startX>= 275) {//限制右边
box.style.left = 275 + "px"
return false
}
if (touch.pageY - startY>= 296) {//限制下边
box.style.top = 296 + "px"
return false
}
if (touch.pageY - startY<= 0) {//限制上边
box.style.top = 0 + "px"
return false
}
if (!isDragging) { // 如果正在拖拽
box.style.left = touch.pageX - startX+ "px";// 设置盒子的left值
box.style.top = touch.pageY - startY+ "px";// 设置盒子的top值
}
})