码迷,mamicode.com
首页 > 编程语言 > 详细

每天一个JavaScript实例-html5拖拽

时间:2014-10-19 23:24:36      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   java   div   2014   

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一个JavaScript实例-html5拖拽</title>
<style>
#drop{
		width:300px;
		height:200px;
		background-color:#f00;
		padding:5px;
		border:2px solid #000;
	}
#item{
	width:100px;
	height:100px;
	background-color:#ff0;
	padding:5px;
	margin:20px;
	border:1px solid #000;
	}
*[draggable=true]{
	-moz-user-select:none;
	-khtml-user-drag:element;
	cursor:move;
	}
*:-khtml-drag{
		background-color:rgba(238,238,238,0.5);
	}
</style>
<script>

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;
			
				}
	}
	
	//取消事件
	function cancelEvent (event){
		console.log("取消事件");
		if(event.preventDefault){
				event.preventDefault();
			}else{
					event.returnValue = false;
				}
		}
		//取消传递
		function cancelPropagation(event){
			console.log("取消传递");
			if(event.stopPropagation){
					event.stopPropagation();
				}else{
						event.cancelBubble = true;
					}
			
			}
		function dragOver(evt){
		console.log("拖拽进入区域");
			if(evt.preventDefault) 
			evt.preventDefault();
			evt = evt || window.event;
			evt.dataTransfer.dropEffect = 'copy';
			return false;
		}
	window.onload = function(){
			console.log("程序就绪");
			
			//console.log(target);
			var item = document.getElementById("item");
			
			item.setAttribute("draggable","true");
			//console.log(item);
			listenEvent(item,"dragstart",function(evt){
				console.log("拖拽开始");
				evt = evt || window.event;
				evt.dataTransfer.effectAllowed = 'copy';
				evt.dataTransfer.setData("Text",item.id);
				
				});
			var target = document.getElementById("drop");
			listenEvent(target,"dragenter",cancelEvent);
			listenEvent(target,"dragover",dragOver);
			listenEvent(target,"drop",function(evt){
				console.log("drop");
					cancelPropagation(evt);
					evt = evt || window.event;
					evt.dataTransfer.dropEffect = 'copy';
					var id = evt.dataTransfer.getData("Text");
					target.appendChild(document.getElementById(id));
					});
			
			
			
		};
		
</script>
</head>

<body>

<div>
<p>Drag the small yellow box with hte dash border to the larger red box with the solid border</p> 
</div>
<div id = "item" draggable = "true">
</div>
<div id = "drop">
</div>
</body>
</html>

每天一个JavaScript实例-html5拖拽

标签:style   blog   http   color   io   ar   java   div   2014   

原文地址:http://blog.csdn.net/waiting7436/article/details/40270047

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!