在Web开发中,我们要实现拖放效果,需要借助Javascript。今天让我们使用Html5实现它:
先看html核心代码:
<div>
<p>把黄色小方块拖入到红色大方框中</p>
</div>
<div id="item" draggable="true">
</div>
<div id="drop">
</div>
draggable属性是html5新增加的,它有三个值true,false,auto. true是可以拖,false是不可以,auto由用户浏览器是否支持而定。更多请可以参考官方文档.
加上一点儿样式:
<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>
然后我们来看javascript:
1: function listenEvent(eventTarget, eventType, eventHandler) {
2: if (eventTarget.addEventListener) {
3: eventTarget.addEventListener(eventType, eventHandler,false);
4: } else if (eventTarget.attachEvent) {
5: eventType = "on" + eventType;
6: eventTarget.attachEvent(eventType, eventHandler);
7: } else {
8: eventTarget["on" + eventType] = eventHandler;
9: }
10: }
11:
12: // cancel event
13: function cancelEvent (event) {
14: if (event.preventDefault) {
15: event.preventDefault();
16: } else {
17: event.returnValue = false;
18: }
19: }
20:
21: // cancel propagation
22: function cancelPropagation (event) {
23: if (event.stopPropagation) {
24: event.stopPropagation();
25: } else {
26: event.cancelBubble = true;
27: }
28: }
29:
30: window.onload=function() {
31: var target = document.getElementById("drop");
32: listenEvent(target,"dragenter",cancelEvent);
33: listenEvent(target,"dragover", dragOver);
34: listenEvent(target,"drop",function (evt) {
35: cancelPropagation(evt);
36: evt = evt || window.event;
37: evt.dataTransfer.dropEffect = 'copy';
38: var id = evt.dataTransfer.getData("Text");
39: target.appendChild(document.getElementById(id));
40: });
41:
42: var item = document.getElementById("item");
43: item.setAttribute("draggable", "true");
44: listenEvent(item,"dragstart", function(evt) {
45: evt = evt || window.event;
46: evt.dataTransfer.effectAllowed = 'copy';
47: evt.dataTransfer.setData("Text",item.id);
48: });
49:
50: };
51:
52: function dragOver(evt) {
53: if (evt.preventDefault) evt.preventDefault();
54: evt = evt || window.event;
55: evt.dataTransfer.dropEffect = 'copy';
56: return false;
57: }
由上面的代码我们看使用一组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 occurs.
dragleave
Drag leaves target.
dragend
Drag operation ends.
定义了相关的事件,来实现想要功能。上面的Js不难看懂。更多请参考 W3C HTML5
你可以自己试一下,目前在Opera支持最好,IE效果并不好。
希望对您Web开发有帮助.
您可能感兴趣文章:
HTML5上传文件显示进度
Html 5中自定义data-*特性
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。