drag与drop事件

为了支持网页上一些元素的拖动效果,可以使用drag和drog事件。

目前ie 5.0+, firefox 3.5+等都支持这些事件,ECMA Script第5版正式将其纳入标准。

对于被拖动的元素来说,它将依次触发ondragstart和ondrag事件,并在拖放结束时触发ondragend事件。

而对于拖放的目的地元素来说,它将依次触发ondragenter,ondragover,ondrop事件,与mouseover一类的类似。

不过在网页上,只有文本框是默认做为放置目标的(也就是拖的时候显示可以放置的那种图标,而不是“无效”鼠标形状,即圆圈中间加一杠)。

当然,你可以给任意元素添加ondragenter,ondragover事件并把默认操作给阻止掉,那么这个元素就可以接收放置了。此时,你的ondrop事件就会有效。

这里要特别注意,

1)ondragenter和ondragover函数一定要包含event.preventdefault()以阻止默认操作。下文是mozilla原文:

“If the mouse was released over an element that is a valid drop target, that is, one that cancelled the last dragenter or dragover event, then the drop will be successful, and a drop event will fire at the target. Otherwise, the drag operation is cancelled and no drop event is fired.”

https://developer.mozilla.org/En/DragDrop/Drag_Operations#drop

2)这个ondrop效果我今天尝试了很久,一直没有成功,因为我是用return false来代替preventDefault 的。事实上这是不对的。

return false可以实现preventDefault 和stopPropogation的效果。preventDefault will prevent the default event from occuring(取消事件的默认行为), stopPropogation will prevent the event from bubbling up and return false will do both(该方法将停止事件的传播,阻止它被分派到其他 Document 节点。在事件传播的任何阶段都可以调用它。注意,虽然该方法不能阻止同一个 Document 节点上的其他事件句柄被调用,但是它可以阻止把事件分派到其他节点。).

因此,在ondragenter和ondragover函数中不能使用return false。

3)此外,浏览器本身有拖动的默认效果,因此不要在ondragstart中用return false等,这样会阻止了拖动的默认效果。

4)当你的函数本向在要返回布尔时,以下是一个比较全面的写法:

function (eventObject) {    
    if (eventObject.preventDefault) {
        eventObject.preventDefault();
    } else if (window.event) /* for ie */ {
        window.event.returnValue = false;
    }
    return true;
};

原文地址:https://www.cnblogs.com/firstdream/p/4461275.html