对象属性:
对象方法:
Identify what is draggable
function dragstart_handler(ev) { console.log("dragStart"); // Add the target element's id to the data transfer object ev.dataTransfer.setData("text/plain", ev.target.id); } <body> <p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p> </body>
Define the drag's data
function dragstart_handler(ev) { // Add the drag data ev.dataTransfer.setData("text/plain", ev.target.id); ev.dataTransfer.setData("text/html", "<p>Example paragraph</p>"); ev.dataTransfer.setData("text/uri-list", "http://developer.mozilla.org"); }
Define the drag image
function dragstart_handler(ev) { // Create an image and then use it for the drag image. // NOTE: change "example.gif" to an existing image or the image // will not be created and the default drag image will be used. var img = new Image(); img.src = 'example.gif'; ev.dataTransfer.setDragImage(img, 10, 10); }
Define the drag effect
function dragstart_handler(ev) { // Set the drag effect to copy ev.dataTransfer.dropEffect = "copy"; }
Define a drop zone
function dragover_handler(ev) { ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } <body> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> </body>
火狐浏览器拖拽问题
但是进行到这儿在火狐浏览器中发现一个问题:
html5的拖拽,用了preventDefault防止弹出新页面,但在火狐下不管用?
解决办法:
document.body.ondrop = function (event) { event.preventDefault(); event.stopPropagation(); }
或者对于上面的实例中,添加到ondrop方法里面也是可以的:
function drop(ev){ ev.preventDefault(); ev.stopPropagation(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。