原生js 多个div拖拽互换位置
程序员文章站
2022-03-08 10:17:20
...
用原生js实现多个div拖拽互换位置
html代码
<div id="big">
<div class="lit" draggable="true">1</div>
<div class="lit" draggable="true">2</div>
<div class="lit" draggable="true">3</div>
<div class="lit" draggable="true">4</div>
<div class="lit" draggable="true">5</div>
<div class="lit" draggable="true">6</div>
<div class="lit" draggable="true">7</div>
<div class="lit" draggable="true">8</div>
</div>
css样式 采用flex布局
#big{
margin: 0 auto;
width: 400px;
height: 200px;
background-color: beige;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
align-content: space-around;
}
.lit{
border: 1px solid #789;
width: 80px;
height: 80px;
}
js部分
//获取小方块
var lit = document.getElementsByClassName("lit");
var con = null;
for(let i=0; i<lit.length; i++){
//拖动时,用con保存lit
lit[i].ondragstart = function(){
con = this;
}
lit[i].ondragover = function(){
event.preventDefault();
}
//拖动结束时,在当前位置下 进行drop事件
var big = document.getElementById("big")
lit[i].ondrop = function(){
if(con != null && con!=this){
var abc = document.createElement("div");
big.replaceChild(abc,this);
big.replaceChild(this,con);
big.replaceChild(con,abc)
}
}
}
fall in love with hzx at first sight