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>
相关推荐
养老不躺平3 分钟前
关于nest项目打包
前端·javascript
fdc20178 分钟前
Avalonia:使用附加属性实现命令与事件的绑定
javascript·windows·microsoft
Mike_jia1 小时前
uuWAF:开源Web应用防火墙新标杆——从工业级防护到智能防御实战解析
前端
掘金安东尼1 小时前
Chrome 17 岁了——我们的浏览器简史
前端·javascript·github
袁煦丞1 小时前
群晖NAS FTP远程文件仓库全球访问:cpolar内网穿透实验室第524个成功挑战
前端·程序员·远程工作
前端小巷子1 小时前
JS 打造动态表格
前端·javascript·面试
excel1 小时前
从卷积到全连接:用示例理解 CNN 的分层
前端
UNbuff_01 小时前
HTML 各种事件的使用说明书
前端·html
Mr. Cao code1 小时前
探索OpenResty:高性能Web开发利器
linux·运维·服务器·前端·nginx·ubuntu·openresty
li35749 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron