简体   繁体   中英

Move DIV with JavaScript inside BODY's limits

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:

  • Read the Viewport Height and Width ( or like this in jQuery );
  • get the object, not the style ( block = document.getElementById('box') );
  • read block.offsetTop and block.offsetLeft instead of style.top and style.left ;
  • before setting the new value, check that is larger than 0 and that the new value PLUS the box width and height is NOT over the Viewport's height or width, ;
  • set the style.top and style.left as you are doing, by adding "px";

> Running Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM