日期:2014-05-16  浏览次数:20312 次

键盘控制div的简单移动问题,急急急在线等
想实现用键盘的上下左右控制一个小div的移动。但在防止div溢出的时候(函数limit)出现了问题。
如何限定div只在某一个范围(棋盘)内移动,而不是整个屏幕?感激不尽!
<html>
<head>
<script>

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 +
"<div style='position:absolute;background-color:" +
color + ";top:"+ r*picSize + "px;left:"+ c*picSize + "px; width:" + 
picSize + "px; height:" + picSize + "px;' id = " + 'r' + r + 'c' + c +
"></div>";
}
}
s = "<div id='alldiv' style='position:relative;left:700px; width:500px; height:500px; top:100px'>" + s + "</div>";
document.getElementById("boarddiv").innerHTML = s;
}

function movediv()
{
    //获取 ID 为 Box 的元素
    var oBox = document.getElementById("box");
     
    //申明变量
    var bLeft = bTop = bRight = bBottom = false;
     
    //setInterval(code, millisec) - 按照指定的周期(以毫秒计)来调用函数
    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();
        },
    150);
&