作者在 2011-10-31 15:52:22 发布以下内容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>拼图</title>
</head>
<style type="text/css">
div {
border:#000000;
border:thin solid 1px;}
</style>
<script type="text/javascript">
/*
move 函数 提供img标记交换图片的SRC
参数 num 是img标记的编号
*/
function rand(R)
{
return Math.ceil(Math.random()*(R+1))-1
}
//这个函数用于把数组里的内容打乱!
function arrayRand()
{
var nums = new Array(1,2,3,4,5,6,7,8,9);
//alert("fs");
var arrayN=nums.length;
var newArray="";
var copyA=nums;
for (AI=0;AI<=arrayN-1;AI=AI)
{
//alert(AI);
RN=rand(arrayN-1);
//alert(RN);
var arraySplice=copyA.splice(RN,1);
//alert('--'+arraySplice);
newArray+=arraySplice.toString()+",";
arrayN--;
}
newArray=newArray.split(',');
newArray.pop();
//alert(newArray);
for(i=0;i<newArray.length;i++){
img = document.getElementById("img"+(i+1));
//alert(img.alt+" "+img.src);
img.alt = newArray[i]+"";
img.src = newArray[i]+".JPG";
}
}
function move( num ){
//标记是否过关 默认为过关
var flag=true;
//根据 编号获得点击的img元素 该元素的id 为 “img1" - "img9"
var img = document.getElementById("img"+num);
var tids; //定义数组
//根据num的不同值 确定要访问的img元素
if(num == 5){
//点击了 5 后 要访问 上 下 左 右
tids = new Array("img"+(num+1),"img"+(num-1),"img"+(num+3),"img"+(num-3));
}
if(num ==4){
//点击了 4 后 要访问 上 下 右
tids = new Array("img5","img1","img7");
}
if(num == 1){
tids = new Array("img4","img2");
}
if(num == 2){
tids = new Array("img1","img3","img5");
}
if(num == 3){
tids = new Array("img2","img6");
}
if(num == 6){
tids = new Array("img5","img3","img9");
}
if(num == 7){
tids = new Array("img4","img8");
}
if(num == 8){
tids = new Array("img7","img9","img5");
}
if(num == 9){
tids = new Array("img6","img8");
}
//循环遍历数组 看其中有没有alt属性为9的 如果有就交换 图片链接 和alt的值
for(i=0;i<tids.length;i++){
var temimg = document.getElementById(tids[i])
if(temimg == null){
continue;
}
if(temimg.alt == "9"){
var path = img.src;
var aalt = img.alt;
img.src = temimg.src;
img.alt=temimg.alt;
temimg.src=path;
temimg.alt = aalt;
break;
}
}
//判断是否将 alt 为 1 的图片放到了img1元素里 依次类推
for(i =1;i<=9;i++){
var img = document.getElementById("img"+i);
if(img.alt != i){
// 如果img.alt != 图片的的编号 那么就还没有将所有的图片位置摆放正确
flag = false;
break;
}
} // 循环结束后就确定了 flag 还是不是 true 如果是那么就过关了
if(flag == true){
alert("恭喜过关!!")
}
}
</script>
<body>
<input type="button" value="开始" onclick="arrayRand()" />
<div id="pan" style="position:absolute; left:200px; top:100px; width:300px; height:300px; background:#CCCCCC;">
<div id="lab1" style="position:absolute; left:0px; top:0px; width:100px; height:100px;">
<img id="img1" src="1.JPG" alt="1" width="100" height="100" onclick="move(1)"/>
<div id="lab2" style="position:absolute; left:100px; top:0px; width:100px; height:100px;">
<img id="img2" src="2.JPG" alt="2" width="100" height="100" onclick="move(2)"/>