LoginSignup
10
10

More than 5 years have passed since last update.

タッチイベントを拾ってDraggableモドキ

Posted at

jQuery UIのDraggableだとiPhoneだとかのタッチデバイスでドラッグできない。
しょぼーん…

いろいろ調べてみたら、touchstart, touchmove, touchendってのでタッチイベントが拾えるらしい。

ということで書いてみた。

touchtest.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>touch test</title>
    <style type="text/css">
    .touchable {
        position: absolute;
        cursor: move;
        width: 100px;
        height: 100px;
        background-color: blue; }
    </style>
</head>
<body>
    <div class="touchable"></div>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

    <script>
    'use strict';

    $('.touchable').bind({
        'touchstart mousedown': function (e) {
            e.preventDefault();

            var eventPos = {};
            if (e.type == 'touchstart') {
                eventPos = {
                    x: e.originalEvent.changedTouches[0].pageX,
                    y: e.originalEvent.changedTouches[0].pageY
                };
            } else {
                eventPos = { x: e.pageX, y: e.pageY };
            }

            this.initialTouchPos = eventPos;
            this.initialDocPos = $(this).position();
            this.touching = true;
        },
        'touchmove mousemove': function (e) {
            if (!this.touching) return;
            e.preventDefault();

            var eventPos;
            if (e.type == 'touchmove') {
                eventPos = {
                    x: e.originalEvent.changedTouches[0].pageX,
                    y: e.originalEvent.changedTouches[0].pageY
                };
            } else {
                eventPos = { x: e.pageX, y: e.pageY };
            }

            var left = this.initialDocPos.left
                    + (eventPos.x - this.initialTouchPos.x);
            var top = this.initialDocPos.top
                    + (eventPos.y - this.initialTouchPos.y);

            $(this).css({ left: left, top: top });
        },
        'touchend mouseup': function (e) {
            if (!this.touching) return;
            this.touching = false;
            delete this.touching;
            delete this.initialTouchPos;
            delete this.initialDocPos;
        }
    });
    </script>
</body>
</html>

touchstart時点の座標を覚えておいて、touchmoveが発生毎に、開始時の座標との差分をターゲットドキュメントの座標に加えてあげるだけ。thisに勝手なプロパティ追加したので最後に一応お掃除deleteしてみました。(しなくてもいいのかな?良くわかんない)

タッチイベント発生時の座標は、e.originalEvent.changedTouches[0]から引っ張ってこないといけないみたい。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10