2

My purpose is to move a DIV (box) within BODY's limits with JavaScript. It consists of 4 buttons, each one of them move the DIV vertically and horizontally (minus and plus values passed by the OnClick events).

My code is as follows (it doesn't work :( ):

<style>

#box {
    z-index: 2;
    position: absolute; 
    top: 200px; 
    left: 300px;
    width: 100px; 
    height: 227px; 
    border: none;
}

</style>

<script>

function moveV(i) { 

    var block, vTop, vNum;

    block = document.getElementById('box').style;
    vTop = block.top; 
    vNum = parseInt(vTop); 

    vNum += i; 
    block.top = vNum + "px"; 
} 

</script>

<input type="button" id="btn1" class="btn" onClick="moveV(-20);">
<input type="button" id="btn2" class="btn" onClick="moveH(-20);">
<input type="button" id="btn3" class="btn" onClick="moveV(20);">
<input type="button" id="btn4" class="btn" onClick="moveH(20);">

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

Also, another problem is that I don't know how to make it stop once you reach the body limit. Should I put it in another DIV so the limits are "tangible"?

4

2 回答 2

3

使用 jQuery 会更好,顺便说一下,使用直接的 javascript 会是:

  • 阅读视口高度和宽度或像 jQuery 中的这样);
  • 获取对象,而不是样式 ( block = document.getElementById('box'));
  • 阅读block.offsetTopandblock.offsetLeft而不是style.topand style.left;
  • 在设置新值之前,检查它是否大于 0,并且新值加上框的宽度和高度不超过视口的高度或宽度,;
  • 通过添加“px”来设置style.topandstyle.left你正在做的事情;

> 运行演示

于 2013-05-27T16:53:03.420 回答
1

你可以使用jquery:

function moveV(i) { 
    $("#box").animate({top:"+="+i+"px"});
}
function moveH(i) { 
    $("#box").animate({left:"+="+i+"px"});
}

有用。

于 2013-05-27T16:17:49.407 回答