dom操做元素的拖拽drag多元素

生命週期:
        dragstart-drag-dragenter-dragover-drop-dragendhtml

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>多元素拖拽</title>
	<style>
		body{
			height: 400px;
		}
		.parent{
			border:1px solid red;
			margin: 10px;
			height: 100px;
		}
		.child{
			border:1px solid blue;
			margin:10px;
			height: 50px;
			width: 50px;
			display: inline-block;
		}
	</style>
	<script>
		window.onload = function(){
			var body = document.body;
			var parents = document.getElementsByClassName('parent');
			parents = Array.prototype.slice.call(parents,0);
			var childs = document.getElementsByClassName('child');
			childs = Array.prototype.slice.call(childs,0);
			// dragstart事件處理程序
			function dragStart(event){
				var dt = event.dataTransfer;
				// 設置視覺效果
				// dt.effectAllowed = 'link';
				var img = new Image();
				img.src = '../1.jpg';
				dt.setDragImage(img,100,100);
				dt.setData('text/plain',this.id);
			}
			// 綁定事件
			childs.forEach(function(item){
				item.draggable = 'true';
				item.ondragstart = dragStart;
			});
			// 在放置元素的內部移動,將放置元素設置成可放置的
			function dragOver(event){
				event.preventDefault();
			}
			// 放置事件的處理函數,放置
			function drop(event){
				var dt = event.dataTransfer;
				var id = dt.getData('text/plain');
				var node = document.getElementById(id);
				this.appendChild(node);	
				event.stopPropagation();
				event.preventDefault();
			}
			parents.forEach(function(item){
				item.ondragover = dragOver;
				item.ondrop = drop;
			});
			body.ondragover = dragOver;
			body.ondrop = drop;
		}
	</script>
</head>
<body>
	<div class="parent"></div>
	<div class="parent"></div>
	<div class="child" id="one">one</div>
	<div class="child" id="two">two</div>
	<div class="child" id="three">three</div>
	<div class="child" id="four">four</div>
	<div class="child" id="five">five</div>
</body>
</html>
相關文章
相關標籤/搜索