在Web開發中,我們要實作拖放效果,需要藉助Javascript。今天讓我們使用Html5實現它:
先看html核心代碼:
draggable屬性是html5新增加的,它有三個值true,false,auto. true是可以拖,false是不可以,auto由用戶瀏覽器是否支援而定。更多請可以參考官方文檔.
加上一點兒樣式:
然後我們來看看javascript:
然後我們就來看javascript
程式碼如下:
function listenEvent(eventTarget, eventType, eventHandler) { (event. {
eventTarget.addEventListener(eventType, eventHandler,false);
} else if (eventTarget.attachEvent) {
eventType = "on" eventType;
eventTarget.attachEvent(eventType, eventType = "on" eventType;
eventTarget.attachEvent(eventType, eventHandler); 🎜>} else {
eventTarget["on" eventType] = eventHandler;
}
}
// cancel event
function cancelEvent (event) { if (event.preDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
// cancel propagation
function
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
window.onload=function. () {
var target = document.getElementById("drop");
listenEvent(target,"dragenter",cancelEvent);
listenEvent(target,"dragover", dEventAver);
listenEvent(target,"dragover", dEventAver);
listen (target,"drop",function (evt) {
cancelPropagation(evt);
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
var id = evt.dataTransfer.getData("Text");
target.appendChild(document.getElementById(id));
});
var item = document.getElementById("item");
item.setAttribute("draggable", "true");
listenEvent(item,"dragstart", function(evt) {
evt = evt || window.event;
evt.dataTransfer.effectAllowed = 'copy';
evt.dataTransfer.setData("Text",item.id);
});
};
function dragOver(evt) {
if (evt. preventDefault) evt.preventDefault();
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
return false;
}
}
🎜>由上面的程式碼我們看使用一組HTML5 提供的拖放Events,直接來看下面:
dragstart
Drag event starts.
drag
During the drag operation.
dragenter
Drag is over the target; used to determine if target will accept drop.
dragover
Drag is over target; used to determine feedback to user.
drop
>drop. dragleave
Drag leaves target.
dragend
Drag operation ends. 定義了相關的事件,來實現想要功能。上面的Js不難看懂。 你可以自己試試看,目前在Opera支援最好,IE效果並不好。 希望對您Web開發有幫助.