效果图
drag_img.png
JS部分
import React, { FC, useEffect } from 'react'
import './index.less'
interface IProps {}
const DragDom:FC<IProps> = (props) => {
useEffect(() => {
setTimeout(() => {
//获取bg类的div列表
var box = document.querySelector('.bg')?.getElementsByTagName('div')
var content: any = null //当前box的内容记录变量
if (!box) return
console.log('可以拖拽了', box)
for (let i = 0; i < box.length; i++) {
//设置开始拖拽时的函数(记录当前box内容)
box[i].ondragstart = function() {
content = this
console.log('ondragstart', content)
}
//阻止默认的事件,event来源JS已定义的变量
box[i].ondragover = function(event) {
event.preventDefault()
console.log('ondragover')
}
//结束拖拽后的处理信息
box[i].ondrop = function() {
console.log('ondrop', this)
if (content != null && content != this) {
let temp = document.createElement('div')
// 基础的交换写法
// @ts-ignore
document.querySelector('.bg')?.replaceChild(temp, this)
// @ts-ignore
document.querySelector('.bg')?.replaceChild(this, content)
document.querySelector('.bg')?.replaceChild(content, temp)
}
}
}
}, 1000)
}, [])
return (
<>
<div className="bg">
<div className="box1" draggable={true}>
1
</div>
<div className="box2" draggable={true}>
2
</div>
<div className="box3" draggable={true}>
3
</div>
<div className="box4" draggable={true}>
4
</div>
<div className="box5" draggable={true}>
5
</div>
<div className="box6" draggable={true}>
6
</div>
<div className="box7" draggable={true}>
7
</div>
<div className="box8" draggable={true}>
8
</div>
</div>
</>
)
}
export default DragDom
CSS部分
.bg {
width: 750px;
height: 750px;
background: #000;
position: fixed;
left: 0;
top: 0;
z-index: 10000;
div {
width: 25%;
height: 50%;
float: left;
display: flex;
justify-content: center;
align-items: center;
font-size: 50px;
color: #fff;
}
}
.box1 {
background: rgb(250, 230, 77);
}
.box2 {
background: rgb(208, 113, 4);
}
.box3 {
background: rgb(124, 248, 70);
}
.box4 {
background: rgb(49, 239, 239);
}
.box5 {
background: rgb(59, 80, 240);
}
.box6 {
background: rgb(237, 71, 237);
}
.box7 {
background: rgb(228, 23, 108);
}
.box8 {
background: rgb(31, 55, 31);
}
网友评论