[英]Move DIV with JavaScript inside BODY's limits
My purpose is to move a DIV (box) within BODY's limits with JavaScript. 我的目的是使用JavaScript在BODY的限制范围内移动DIV(框)。 It consists of 4 buttons, each one of them move the DIV vertically and horizontally (minus and plus values passed by the OnClick events).
它由4个按钮组成,每个按钮均沿水平和垂直方向移动DIV(OnClick事件传递的负值和加值)。
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"?
我应该把它放在另一个DIV中,这样限制才是“有形的”吗?
It would be better to use jQuery, by the way with straight javascript it would be: 最好使用jQuery,顺便说一下javascript,它是:
block = document.getElementById('box')
); block = document.getElementById('box')
); block.offsetTop
and block.offsetLeft
instead of style.top
and style.left
; block.offsetTop
和block.offsetLeft
而不是style.top
和style.left
; style.top
and style.left
as you are doing, by adding "px"; style.top
和style.left
; you can use jquery: 您可以使用jquery:
function moveV(i) {
$("#box").animate({top:"+="+i+"px"});
}
function moveH(i) {
$("#box").animate({left:"+="+i+"px"});
}
it works. 有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.