点评:不使用javascript实现拖放效果,一直以来都是网友们所希望看到的,二今天html5却做到了接下来详细为您介绍,需要了解的朋友可以参考下
在Web开发中,我们要实现拖放效果,需要借助Javascript。今天让我们使用Html5实现它:
先看html核心代码:
复制代码
代码如下:
<div>
<p>把黄色小方块拖入到红色大方框中</p>
</div>
<div draggable="true">
</div>
<div>
</div>
复制代码
代码如下:
<style type="text/css">
#drop
{
width: 300px;
height: 200px;
background-color: #ff0000;
padding: 5px;
border: 2px solid #000000;
}
#item
{
width: 100px;
height: 100px;
background-color: #ffff00;
padding: 5px;
margin: 20px;
border: 1px dashed #000000;
}
*[draggable=true] {
-moz-user-select:none;
-khtml-user-drag: element;
cursor: move;
}
*:-khtml-drag {
background-color: rgba(238,238,238, 0.5);
}
</style>
复制代码
代码如下:
function listenEvent(eventTarget, eventType, eventHandler) {
if (eventTarget.addEventListener) {
eventTarget.addEventListener(eventType, eventHandler,false);
} else if (eventTarget.attachEvent) {
eventType = "on" + eventType;
eventTarget.attachEvent(eventType, eventHandler);
} else {
eventTarget["on" + eventType] = eventHandler;
}
}
// cancel event
function cancelEvent (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
// cancel propagation
function cancelPropagation (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
window.onload=function() {
var target = document.getElementById("drop");
listenEvent(target,"dragenter",cancelEvent);
listenEvent(target,"dragover", dragOver);
listenEvent(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;
}
新闻热点
疑难解答