九宫格拖拽效果
关于一些拼图游戏什么的,见人家效果做的不错,参考下别人写的代码,我也尝试着做了个。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
#wrap{
position: relative;
}
#wrap div{
position: absolute;
width: 100px;
height: 100px;
font-size: 50px;
text-align: center;
line-height: 100px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="wrap"></div>
<script type="text/javascript">
//生成结构
var oWrap = document.getElementById("wrap");
var mt = ml = 10;
for(var i = 0; i < 3; i++){
for(var j = 0; j < 3; j++){
var oDiv = document.createElement("div");
oWrap.appendChild(oDiv);
oDiv.style.top = i*(oDiv.offsetHeight + mt) + "px";
oDiv.style.left = j*(oDiv.offsetWidth + ml) + "px";
oDiv.style.backgroundColor = "rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")"
}
}
var arr = "ABCDEFGHI";
var aItems = oWrap.children;
var len = aItems.length;
for(var i = 0; i < aItems.length; i++){
aItems[i].innerHTML = arr[i];
}
//拖拽及交换位置
for(var i = 0; i < aItems.length; i++){
aItems[i].onmousedown = function(e){
var evt = e || event;
var x = evt.offsetX;
var y = evt.offsetY;
/*var x = evt.clientX - this.offsetLeft - oWrap.offsetLeft;
var y = evt.clientY - this.offsetTop - oWrap.offsetTop;*/
var _this = this;
var cloneNode = this.cloneNode();
cloneNode.style.border = '1px dashed #cecece';
this.style.zIndex = 1;
oWrap.replaceChild(cloneNode,this);
oWrap.appendChild(this);
document.onmousemove = function(e){
var evt = e || event;
var _left = evt.clientX - x - oWrap.offsetLeft;
var _top = evt.clientY - y - oWrap.offsetTop;
_this.style.left = _left + "px";
_this.style.top = _top + "px";
return false;
}
document.onmouseup = function(){
//交换位置
var disArr = [];
var newArr = [];
console.log(aItems.length);
for(var i = 0; i < len; i++){
var disX = _this.offsetLeft - aItems[i].offsetLeft;
var disY = _this.offsetTop - aItems[i].offsetTop;
var dis = Math.sqrt(Math.pow(disX,2)+Math.pow(disY,2));
disArr.push(dis);
newArr.push(dis);
}
disArr.sort(function(a,b){
return a-b;
})
var minIndex = newArr.indexOf(disArr[0]);
_this.style.left = aItems[minIndex].style.left;
_this.style.top = aItems[minIndex].style.top;
aItems[minIndex].style.left = cloneNode.style.left;
aItems[minIndex].style.top = cloneNode.style.top;
oWrap.removeChild(cloneNode);
document.onmousemove = null;
document.onmouseup = null;
}
}
}
/*var arr = [45,32,11,90];
var minVal = Math.min.apply(null,arr);
var minIndex = arr.indexOf(minVal);
console.log(minVal,arr,minIndex);*/
</script>
</body>
</html>
这是效果图
虽说实现了效果,但我写的还是不太严谨,还有诸多bug,比如上边做边没距离,实际写的话还要加上这个距离,即使距离为0,还有就是我发现拖拽的时候,如果使用qq截图的话,克隆的那个小方块没办法消失,只得重新刷新页面,有没有大佬解决下