我在 w3schools 上找到了这段用于拖放的代码,它适用于桌面设备,但不适用于移动设备。
我需要修改什么才能识别触摸?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
<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>
</head>
<body>
<p>Drag the W3Schools image into the rectangle:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
</body>
</html>
大多数移动设备不监听绑定(bind)到 DOM 的拖动事件。我会推荐使用 touchmove 事件和伴随它的事件。它看起来像:
选项 1
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
</head>
<body>
<p>Drag the W3Schools image into the rectangle:</p>
<div id="div1"></div>
<br>
<img id="drag1" src="img_logo.gif width="336" height="69">
<script type="text/javascript">
var el = document.getElementById('drag');
el.addEventListener("touchstart", handleStart, false);
el.addEventListener("touchend", handleEnd, false);
el.addEventListener("touchcancel", handleCancel, false);
el.addEventListener("touchleave", handleEnd, false);
el.addEventListener("touchmove", handleMove, false);
function handleStart(event) {
// Handle the start of the touch
}
// ^ Do the same for the rest of the events
</script>
</body>
</html>
handleStart、handleEnd 等是您从事件中触发的回调,您可以在其中处理触摸事件。
如果您不想完成触摸事件方面的所有繁重工作,那么我会推荐一个库,例如 JQuery Touch Punch。我用过它,它在 iOS 上运行良好。
这是库的链接,您还可以在您自己的移动设备上测试它的性能:http://touchpunch.furf.com/
选项 2(更好的选项)
JQuery Touch punch 是这样包含的:
在您的页面上包含 jQuery 和 jQuery UI。
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script>
// Download this from the link above
<script src="jquery.ui.touch-punch.min.js"></script>
<script>
$('#drag1').draggable();
$( "#div1" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "isDropped" )
.html( "Dropped!" );
}
});
});
</script>