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"?
It would be better to use jQuery, by the way with straight javascript it would be:
block = document.getElementById('box')
); block.offsetTop
and block.offsetLeft
instead of style.top
and style.left
; style.top
and style.left
as you are doing, by adding "px"; you can use jquery:
function moveV(i) {
$("#box").animate({top:"+="+i+"px"});
}
function moveH(i) {
$("#box").animate({left:"+="+i+"px"});
}
it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.