JavaScript 之DOM案例(拼图)

JavaScript案例拼图


经过上次的打方块的练习对dom操作稍微熟悉了一些,经过这么久的酝酿。。。。
上代码
样式部分,针对内部的十六块div的操作这里不多BB

<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		html,body{
			height: 100%;
			width: 100%;
			float: left;
		}
		#box{
			width: 800px;
			height: 800px;
			margin: 50px auto;
			border: 5px solid #7FFF00;
		}
		#box>div{
			width: 200px;
			height: 200px;
			float: left;
		}
		#box>div>div{
			width: 100%;
			height: 100%;
			display: flex;
			box-sizing: border-box;
			border: 1px solid white;
			justify-content: center;
			align-items: center;
			-webkit-user-select: none;
			cursor: pointer;
		}
	</style>

结构部分

<div id="box">
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
		<div></div>
	</div>

正题来了,js代码
主要算法思想是利用每个方格能移动的位置记录下来,并且在触发点击事件时逐个遍历

	window.onload=function(){
		new Gigsaw();
	}
	
	function Gigsaw(){
		this.Box = document.querySelector('#box');
		this.BoxItem = document.querySelectorAll('#box > div');
		this.Pos=[]//存储每个方块可能移动到的位置
		this.Pos[0]  = [1,4];//如第一块移动的位置只能到序号为1和序号为4的方格
		this.Pos[1]  = [0,2,5];
		this.Pos[2]  = [1,3,6];
		this.Pos[3]  = [2,7];
		this.Pos[4]  = [0,5,8];
		this.Pos[5]  = [1,4,6,9];
		this.Pos[6]  = [2,5,7,10];
		this.Pos[7]  = [3,6,11];
		this.Pos[8]  = [4,9,12];
		this.Pos[9]  = [5,8,10,13];
		this.Pos[10] = [6,9,11,14];
		this.Pos[11] = [7,10,15];
		this.Pos[12] = [8,13];
		this.Pos[13] = [9,12,14];
		this.Pos[14] = [10,13,15];
		this.Pos[15] = [11,14];
		this.init();
	}
	
	Gigsaw.prototype.init=function(){
		for(var i=0;i<this.BoxItem.length-1;i++){
			var NewBox = document.createElement('div');//生成移动的方块
			NewBox.style.backgroundImage = `url(img/16/16${i}.png)`;//方块上的小图片路径通过拼串
			this.bindClickEvent(NewBox);//给方块加上点击事件
			this.BoxItem[i].appendChild(NewBox);
			this.BoxItem[i].index = i;//给盒子加上索引
		}
		this.BoxItem[i].index=this.BoxItem.length-1;//拼图的最后会少一块,但是是可以移动到的,最后一个单独记录
	}
	
	Gigsaw.prototype.bindClickEvent=function(Ele){
		var that = this;
		Ele.onclick=function(){
			var index = this.parentNode.index;//当前元素的盒子的索引
			for(var i=0;i<that.Pos[index].length;i++){//和存放方格的能移动位置的数组循环对比
				if(that.BoxItem[that.Pos[index][i]].innerHTML==""){//如果当前的位置是空的
					that.BoxItem[that.Pos[index][i]].appendChild(this);//则将当前元素加入到当前的空格子中
					break;//跳出循环节省性能
				}
			}
		}
	}

实现效果
在这里插入图片描述
思路简单实现手法简单,用来练手的好东西,虽然这个游戏我自己就没拼全乎过(手动滑稽)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值