<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖动替换</title>
</head>
<style>
body {
display: flex;
padding: 100px;
}
div {
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
color: white;
margin-right: 10px;
}
</style>
<body>
<div style="background: purple;" draggable="true">div1</div>
<div style="background: orange;" draggable="true">div2</div>
<div style="background: aqua;" draggable="true">div3</div>
</body>
</html>
<script>
//获取所有div
let div = document.getElementsByTagName("div");
let container = null; //用一个容器来存放拖动的div
for (let i = 0; i < div.length; i++) {
//当开始拖动的时候把拖动的div用container保存
div[i].ondragstart = function () {
container = this;
}
//默认的当你dragover的时候阻止你做drop的操作,所以需要取消这个默认
div[i].ondragover = function () {
event.preventDefault();
}
//当拖动结束的时候,给拖动div所在位置下面的div做drop事件
div[i].ondrop = function () {
if (container != null && container != this) {
let temp = document.createElement("div");
document.body.replaceChild(temp, this);
document.body.replaceChild(this, container);
document.body.replaceChild(container, temp);
}
}
}
</script>
JS_js实现拖动DIV交换位置
猜你喜欢
转载自blog.csdn.net/weixin_44599931/article/details/120267705
今日推荐
周排行