html实现元素拖动替换

效果

html实现元素拖动替换_第1张图片

实现

复制粘贴.html即可使用

DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>拖动替换title>
	head>
	<style>
		.box {
			width: 500px;
			height: 500px;
			background: gainsboro;
			border-radius: 10px;
		}
		
		.tuodong {
			width: 50px;
			height: 50px;
			background: dodgerblue;
			margin: 15px;
			cursor: pointer;
			border-radius: 5px;
			font-size: 14px;
			line-height: 50px;
			text-align: center;
			color: #fff;
		}
	style>

	<body>
		<div id="app">
			<div class="box" ondrop="handleDrag(event, this)" ondragover="handleDragover(event, this)" ondragleave="handleDragleave(event, this)" id="dropZone">
			div>
			<div class="tuodong" id="id1" draggable="true" ondragend="dragEnd(event, this)" ondragstart="dragStart(event, this)">
				来拖我
			div>
		div>
	body>
	<script src="js/jquery-3.2.1.min.js">script>
	<script>
		function dragStart(event, _serf) {
			console.log(event.target.id)
			console.log("拖动")
		}

		function dragEnd(event, _serf) {
			console.log("松开")
		}

		function handleDrag(event, _serf) {
			console.log("你贴我脸上了", event.target.id)
			document.getElementById(event.target.id).style.background = 'dodgerblue'
		}

		function handleDragover(event, _serf) {
			console.log("移入", event.target.id)
			document.getElementById(event.target.id).style.background = '#f1f1f1'
		}

		function handleDragleave(event, _serf) {
			console.log("移除", event.target.id)
			document.getElementById(event.target.id).style.background = 'gainsboro'
		}

		// 监听事件添加【阻止网页默认打开文件的动作】
		window.onload = function() {
			document.addEventListener("drop", function(e) { //拖到元素释放
				e.preventDefault();
			});
			document.addEventListener("dragleave", function(e) { //拖离元素
				e.preventDefault();
			});
			document.addEventListener("dragenter", function(e) { //拖进元素
				e.preventDefault();
			});
			document.addEventListener("dragover", function(e) { //拖到元素
				e.preventDefault();
			});
		}
	script>

html>

你可能感兴趣的:(前端,html,javascript,前端,拖动替换)