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>
相关推荐
mCell12 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip12 小时前
Node.js 子进程:child_process
前端·javascript
excel15 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel16 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼18 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping18 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙19 小时前
[译] Composition in CSS
前端·css
白水清风19 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix19 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780019 小时前
new、原型和原型链浅析
前端·javascript