<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#box {
width: 303px;
height: 303px;
margin: 100px auto;
}
#box div {
width: 100px;
height: 100px;
float: left;
margin-left: 1px;
margin-top: 1px;
text-align: center;
line-height: 100px;
font-size: 50px;
color: #FFF;
}
#box div:nth-of-type(1) {
background: #000;
}
#box div:nth-of-type(2) {
background: #f00;
}
#box div:nth-of-type(3) {
background: #0f0;
}
#box div:nth-of-type(4) {
background: #00f;
}
#box div:nth-of-type(5) {
background: #ff0;
}
#box div:nth-of-type(6) {
background: #f0f;
}
#box div:nth-of-type(7) {
background: #0ff;
}
#box div:nth-of-type(8) {
background: pink;
}
#box div:nth-of-type(9) {
background: orange;
}
#box .draging {
position: absolute;
}
</style>
<body>
<div id="box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
<script>
var divs = document.querySelectorAll('#box div')
var box = document.querySelector('#box')
for (var i = 0; i < divs.length; i++) {
var oDiv = divs[i]
oDiv.onmousedown = function (e) {
//div的相对位置
var offsetX = e.offsetX
var offsetY = e.offsetY
var that = this
//创建一个div,可以拖拽
//cloneNode(true)克隆div, 同时复制子元素
var dragDiv = this.cloneNode(true)
console.log(dragDiv)
box.appendChild(dragDiv)
//给创建的div加样式
dragDiv.className = 'draging'
//拿到内部样式表中的样式
console.log(getComputedStyle(this).backgroundColor)
dragDiv.style.backgroundColor = getComputedStyle(this).backgroundColor
//拿到被点击div的坐标
console.log(this.offsetLeft)
console.log(this.offsetTop)
//改变克隆div位置
dragDiv.style.left = this.offsetLeft + 'px'
dragDiv.style.top = this.offsetTop + 'px'
//拖拽
document.onmousemove = function (evt) {
var x = evt.pageX - offsetX
var y = evt.pageY - offsetY
dragDiv.style.left = x + 'px'
dragDiv.style.top = y + 'px'
return false;
}
document.onmouseup = function () {
document.onmousemove = null
//判断dragDiv离哪一个div更近
console.log(divs)
var min = distance(divs[0], dragDiv)
var minIndex = 0
for (var i = 0; i < divs.length; i++) {
var oDiv = divs[i]
//根据勾股定理算出斜边
var c = distance(oDiv, dragDiv)
if (c < min) {
min = c
minIndex = i
}
}
//交换内容和样式
var minDiv = divs[minIndex]
console.log(that)
//交换内容
var tmpText = that.innerHTML
that.innerHTML = minDiv.innerHTML
minDiv.innerHTML = tmpText
//交换样式
var tmpBg = getComputedStyle(that).backgroundColor
that.style.backgroundColor = getComputedStyle(minDiv).backgroundColor
minDiv.style.backgroundColor = tmpBg
//删除克隆div
dragDiv.remove()
}
return false;
}
}
//根据勾股定理算出斜边
function distance(oDiv, dragDiv) {
var a = oDiv.offsetLeft - dragDiv.offsetLeft
var b = oDiv.offsetTop - dragDiv.offsetTop
var c = Math.sqrt(a * a + b * b)
return c
}
</script>
</body>
</html>
原生js九宫格拖拽
最新推荐文章于 2023-07-14 15:22:46 发布