Frage

First of all, I make a responsive site, so I use this drag and drop function both with mouse functions and touch functions. After my searching on the Internet I found this recommendation: http://touchpunch.furf.com/. The only problem is, that this doesn't help me.

I guess it's because JavaScript might be needed.

My code for the normal touch function (with mouse) looks like this:

HTML

<div id="dragzone" ondrop="drop(event)" ondragover="allowDrop(event)">
    <img id="drag1" src="img/perso_paintball.png" draggable="true"
            ondragstart="drag(event)" width="80" height="80">

    <img id="drag2" src="img/family_picture.png" draggable="true"
            ondragstart="drag(event)" width="80" height="80">

    <img id="drag3" src="img/Tøse-hygge.png" draggable="true"
            ondragstart="drag(event)" width="80" height="80">

    <img id="drag4" src="img/romantisk.png" draggable="true"
            ondragstart="drag(event)" width="80" height="80">
</div>

jQuery

<script>
    function allowDrop(ev) {
        ev.preventDefault();
    }

    function drag(ev) {
        ev.dataTransfer.setData("Text", ev.target.id);
    }

    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("Text");
        ev.target.appendChild(document.getElementById(data));
    }
</script>

This code works fine, when I just want to drag and drop a picture from one zone to another. But I've tried every single recommendation to get the touch drag and drop working just like with the mouse.

Do I need to go away from this simple code to some real JavaScript to use this "hack" from touchpunch?

Or can I somehow make this piece of code work with touch as well?

If you want to know then this piece of code is from W3schools. :)

War es hilfreich?

Lösung

Firstival, I would recommend to rid of inline event handlers (e.g: ondragstart="drag(event)").

As I can see, you use html5 drag-and-drop API, which is good but will have issues with browser compatability (for instance, it won't work in IE < 10).

To have it work nice and well in most browsers I would recommend using such jquery-ui widgets as sortable and draggable with touch-punch which in most cases will do the work of handling touch events.

Should you need the example of code invoking draggable functionality, you can find it on jquery-ui website.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top