手机浏览器中实现可拖动div

发布时间 2023-11-04 17:34:14作者: 空明流光
var touchStartX = 0;
var touchStartY = 0;
var moveX = 0;
var moveY = 0;

var div = document.getElementById('yourDivId'); // 获取你要拖动的div

div.addEventListener('touchstart', function(e) {
    var touch = e.touches[0]; // 获取第一个触点
    touchStartX = touch.pageX; // 记录触点初始位置
    touchStartY = touch.pageY;
});

div.addEventListener('touchmove', function(e) {
    e.preventDefault(); // 阻止默认行为
    var touch = e.touches[0]; // 获取第一个触点

    moveX = touch.pageX - touchStartX; // 计算移动距离
    moveY = touch.pageY - touchStartY;

    var newLeft = div.offsetLeft + moveX;
    var newTop = div.offsetTop + moveY;

    // 边界检查
    if (newLeft < 0) newLeft = 0;
    if (newTop < 0) newTop = 0;
    if (newLeft + div.offsetWidth > window.innerWidth) newLeft = window.innerWidth - div.offsetWidth;
    if (newTop + div.offsetHeight > window.innerHeight) newTop = window.innerHeight - div.offsetHeight;

    div.style.left = newLeft + 'px'; // 更新div位置
    div.style.top = newTop + 'px';

    touchStartX = touch.pageX; // 更新触点位置,以便下次计算
    touchStartY = touch.pageY;
});

div.addEventListener('touchend', function(e) {
    // 可以在这里添加你在结束拖动后需要执行的代码
});