鼠标点击拖动小方块,放开点击后小方块自动移入最近的一个固定的规则位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#bigtable{
width: 1040px;
display: flex;
justify-content: start;
flex-wrap: wrap;
}
.tab{
width: 80px;
height: 80px;
border: 1px solid coral;
box-sizing: border-box;
display: inline-block;
font-size: 0;
}
.box{
width: 80px;
height: 80px;
background: coral;
position: fixed;
left: 0;
top: 0;
display: inline-block;
}
</style>
</head>
<body>
<div id="bigtable">
<div class="tab"></div>
</div>
<div class="box"></div>
<script>
var bigtable=document.getElementById('bigtable')
var tab=document.getElementsByClassName('tab')[0]
var newtab=tab.cloneNode(true)
console.log(newtab);
for(var i=0;i<129;i++){
var newtab=tab.cloneNode(true)
bigtable.appendChild(newtab)
}
var box=document.getElementsByClassName('box')[0]
box.onmousedown=function(clickEv){
var x=clickEv.offsetX
var y=clickEv.offsetY
document.onmousemove=function(moveEv){
box.style.left=moveEv.clientX-x+'px'
box.style.top=moveEv.clientY-y+'px'
}
}
document.onmouseup=function(upEv){
var x=box.offsetLeft
var y=box.offsetTop
var numx=Math.round(x/80)
var numy=Math.round(y/80)
x=numx*80+'px'
y=numy*80+'px'
document.onmousemove=function(){
box.style.left=x
box.style.top=y
}
}
</script>
</body>
</html>