-1

我有一个普通的 javascript,用于在 HTML 页面中拖动和移动 DIV 标签这适用于鼠标移动、鼠标向上和鼠标向下事件现在我想扩展它并使其适用于触摸设备(iPhone)有人可以帮我做到这一点

 if (document.getElementById) {

        (function () {

            var n = 500;
            var dragok = false;
            var y, x, d, dy, dx;

            function move(e) {
                if (!e) e = window.event;
                if (dragok) {
                    d.style.left = dx + e.clientX - x + "px";
                    d.style.top = dy + e.clientY - y + "px";
                    return false;
                }
            }

            function down(e) {
                if (!e) e = window.event;
                var temp = (typeof e.target != "undefined") ? e.target : e.srcElement;
                if (temp.tagName != "HTML" | "BODY" && temp.className != "dragclass") {
                    temp = (typeof temp.parentNode != "undefined") ? temp.parentNode : temp.parentElement;
                }
                if (temp.className == "dragclass") {
                    dragok = true;
                    temp.style.zIndex = n++;
                    d = temp;
                    dx = parseInt(temp.style.left + 0);
                    dy = parseInt(temp.style.top + 0);
                    x = e.clientX;
                    y = e.clientY;
                    document.onmousemove = move;
                    return false;
                }
            }

            function up() {
                dragok = false;
                document.onmousemove = null;
            }

            document.onmousedown = down;
            document.onmouseup = up;

            document.body.addEventListener("touchstart", down, true);
            document.body.addEventListener("touchcancel", up, true);
            document.body.addEventListener("touchmove", move, true);


        })();
4

1 回答 1

0

你有事件:touchstart、touchmove 和 touchend。他们将以同样的方式工作

https://developer.mozilla.org/en-US/docs/DOM/Touch_events

实现这一点的最佳方法是通过 Modernizr 之类的库或类似的库来测试浏览器是否能够触摸:

var isTouch = "ontouchstart" in window;

if(isTouch){
   el.addEventListener('touchstart', handlerStart);
   el.addEventListener('touchmove', handlerMove);
   el.addEventListener('touchend', handlerEnd);
} else{
   el.addEventListener('mousedown', handlerStart);
   el.addEventListener('mousemove', handlerMove);
   el.addEventListener('mouseup', handlerEnd);
}

根据您要执行的操作的复杂性,两种情况的处理程序可能相同,但您可能必须为鼠标和触摸使用不同的处理程序

于 2013-02-25T18:23:07.460 回答