html实现元素拖动替换

效果

实现

复制粘贴.html即可使用

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>
相关推荐
沛沛老爹8 小时前
Web开发者进阶AI:企业级Agent Skills安全策略与合规架构实战
前端·人工智能·架构
摘星编程8 小时前
React Native for OpenHarmony 实战:SegmentControl 分段控件详解
javascript·react native·react.js
摘星编程8 小时前
React Native for OpenHarmony 实战:ProgressRing 环形进度详解
javascript·react native·react.js
遗憾随她而去.9 小时前
前端首屏加载时间的度量:FCP、LCP等指标的规范理解
前端
TAEHENGV9 小时前
React Native for OpenHarmony 实战:数学练习实现
javascript·react native·react.js
CDwenhuohuo9 小时前
安卓app巨坑 nvue后者页面要写画笔绘制功能nvue canvas
前端·javascript·vue.js
一只小bit9 小时前
Qt 事件:覆盖介绍、处理、各种类型及运用全详解
前端·c++·qt·cpp
Never_Satisfied9 小时前
在JavaScript / HTML中,HTML元素自定义属性使用指南
开发语言·javascript·html
前端 贾公子9 小时前
husky 9.0升级指南
javascript
人道领域9 小时前
JavaWeb从入门到进阶(前端工程化)
前端