var picSize=50;
var maxR = 500/picSize;
var maxC = 500/picSize;
var colorArray = ["brown","blue","red"];
//建立棋盤
function makeBoard(){
var index;
var color;
var s = "";
for(r = 0; r < maxR; r++){
for(c = 0; c < maxC; c++){
index = Math.floor(Math.random() * colorArray.length);
color = colorArray[index];
s = s +
"
color + ";top:"+ r*picSize + "px;left:"+ c*picSize + "px; width:" +
picSize + "px; height:" + picSize + "px;' id = " + 'r' + r + 'c' + c +
">";
}
}
s = "
" + s + "
";
document.getElementById("boarddiv").innerHTML = s;
}
function movediv()
{
//獲取 ID 為 Box 的元素
var oBox = document.getElementById("box");
//申明變量
var bLeft = bTop = bRight = bBottom = false;
//setInterval(code, millisec) - 按照指定的周期(以毫秒計(jì))來調(diào)用函數(shù)
setInterval(
function () {
//獲取 box 新的 left 距離
if (bLeft) {
oBox.style.left = oBox.offsetLeft - 50 + "px"
} else if (bRight) {
oBox.style.left = oBox.offsetLeft + 50 + "px"
}
//獲取 box 新的 top 距離
if (bTop) {
oBox.style.top??= oBox.offsetTop??- 50 + "px"
} else if(bBottom) {
oBox.style.top??= oBox.offsetTop??+ 50 + "px"
}
//防止溢出
limit();
},
100);
//當(dāng)鍵盤按下的時(shí)候
document.onkeydown = function (event) {
//獲取 event 對象
var event = event || window.event;
switch (event.keyCode) {
case 37:? ? //鍵盤中左鍵(←)
bLeft = true;
break;
case 38:? ? //鍵盤中左鍵(↑)
bTop = true;
break;
case 39:? ? //鍵盤中右鍵(→)
bRight = true;
break;
case 40:? ? //鍵盤中下鍵(↓)
bBottom = true;
break;
}
return false
};
//當(dāng)松開鍵盤的時(shí)候
document.onkeyup = function (event) {
switch ((event || window.event).keyCode) {
case 37:? ? //鍵盤中左鍵(←)
bLeft? ?= false;
break;
case 38:? ? //鍵盤中左鍵(↑)
bTop? ? = false;
break;
case 39:? ? //鍵盤中右鍵(→)
bRight??= false;
break;
case 40:? ? //鍵盤中下鍵(↓)
bBottom = false;
break;
}
};
//防止溢出
function limit() {
var oDiv=document.getElementById('alldiv');
//防止左側(cè)溢出
oBox.offsetLeft??<= 708 && (oBox.style.left = 708);
//防止頂部溢出
oBox.offsetTop??<= 108 && (oBox.style.top??= 108);
//防止右側(cè)溢出
(oBox.offsetLeft??>= oDiv.offsetWidth-oBox.offsetWidth+708)&&(oBox.style.left=oDiv.offsetWidth-oBox.offsetWidth+708+'px');
//防止底部溢出
(oBox.offsetTop??>= oDiv.offsetHeight-oBox.offsetHeight+108)&&(oBox.style.top=oDiv.offsetHeight-oBox.offsetHeight
+108+'px');
}
};