移动端js拖拽

再添加盒子的父级盒子设置相对定位,创建的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值

                }

            })

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值