简体   繁体   English

在BODY的限制内用JavaScript移动DIV

[英]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,它是:

  • Read the Viewport Height and Width ( or like this in jQuery ); 阅读视口的高度和宽度或在jQuery中类似 );
  • get the object, not the style ( block = document.getElementById('box') ); 获取对象,而不是样式( block = document.getElementById('box') );
  • read block.offsetTop and block.offsetLeft instead of style.top and style.left ; 读取block.offsetTopblock.offsetLeft而不是style.topstyle.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, ; 在设置新值之前,请检查该值是否大于0,并确保新值加上框的宽度和高度未超过视口的高度或宽度;
  • set the style.top and style.left as you are doing, by adding "px"; 通过添加“ px”来设置style.topstyle.left

> Running Demo >运行演示

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.

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