jquery~区域内可随意拖动(移动端)

    xiaoxiao2022-07-06  190

    样式css:

    .barrage { width: 70px; height: 70px; position: fixed; top: 0; background: -webkit-gradient(linear, 0 0, 100% 100%, from(#ff0000), to(#0000ff)); border-radius:50%; } .col1 { color: #fff; display: block; padding: 15px; text-align: center; }

    html:

    <div class="barrage"> <span class="col1">随意拖动</span> </div>

    JS:

    var contW = $(".barrage").width(); var contH = $(".barrage").height(); var startX, startY, sX, sY, moveX, moveY; var winW = $(window).width(); var winH = $(window).height(); $(".barrage").on({ //绑定事件 touchstart: function(e) { startX = e.originalEvent.targetTouches[0].pageX; //获取点击点的X坐标 startY = e.originalEvent.targetTouches[0].pageY; //获取点击点的Y坐标 sX = $(this).offset().left; //相对于当前窗口X轴的偏移量 sY = $(this).offset().top; //相对于当前窗口Y轴的偏移量 leftX = startX - sX; //鼠标所能移动的最左端是当前鼠标距div左边距的位置 rightX = winW - contW + leftX; //鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置 topY = startY - sY; //鼠标所能移动最上端是当前鼠标距div上边距的位置 bottomY = winH - contH + topY; //鼠标所能移动最下端是当前窗口距离减去鼠标距div最下端位置 }, touchmove: function(e) { e.preventDefault(); //移动过程中XY轴的坐标要减去margin的距离 moveX = e.originalEvent.targetTouches[0].pageX; //移动过程中X轴的坐标 moveY = e.originalEvent.targetTouches[0].pageY; //移动过程中Y轴的坐标 //判断的时候要计算加上padding的距离 if(moveX < leftX) { moveX = leftX; } if(moveX > rightX) { moveX = rightX; } if(moveY < topY) { moveY = topY; } if(moveY > bottomY) { moveY = bottomY; } $(this).css({ "left": moveX + sX - startX, "top": moveY + sY - startY, }) }, })

    demo地址

    最新回复(0)