簡體   English   中英

我想阻止我的div移動

[英]I want to stop my div from moving

我有一個代碼,可通過單擊按鈕使瓶子中的水位上升或下降。 但是,如果不單擊停止,就無法停止。 我需要它在清空時基本重置,並且水位的div不會低於特定點(或高於特定點)。 如果您對我的工作感興趣; 我正在制作酒精模擬器。 因此,您基本上會看到酒精飲料的水位下降(即100像素),而降低100像素意味着您可以看到胃中的水位(酒精度)為50像素,而等於20像素。血液循環和大腦中的10 px。 (只是想一個主意。)

但是,如果我單擊下降按鈕,則div只會離開瓶子,並且將有無盡的旅程。 (請使用js,而不是jquery)

這是我的JS代碼:

function move_img(str) {
var step=2 ; // change this to different step value
switch(str){
case "down":
var x=document.getElementById('i1').offsetTop;
x= x + step;
document.getElementById('i1').style.top= x - 1 + "px";
break;

case "up":
var x=document.getElementById('i1').offsetTop;
x= x -step;
document.getElementById('i1').style.top= x + "px";
break;

case "left":
var y=document.getElementById('i1').offsetLeft;
y= y - step;
document.getElementById('i1').style.left= y + "px";
break;

case "right":
var y=document.getElementById('i1').offsetLeft;
y= y + step;
document.getElementById('i1').style.left= y + "px";
break;
}
}


function auto(str) {
 myVar = setInterval(function(){ move_img(str); }, 2)  ;


}
setTimeout(function( ) { clearInterval( myVar ); }, 1);
function nana(){


}

你的小提琴不起作用。 您需要指定高度以及top屬性,我相信top必須在bottom之上。 我在這里舉了一個例子。 對示例所做的更改是:

//javascript
if (str == 'up' || str == 'down') {
    var top = el.offsetTop;
    var height = el.offsetHeight;  //get height to modify
    console.log(height);
    if (str == 'up') {
        top -= step;
        height += step;  //adjust height
    } else {
        top += step;
        height -=step;  //adjust height
    }
    if (top_max >= top && top >= 0) {  //make sure #i1 is inside #i
        document.getElementById('i1').style.top = top + "px";
        document.getElementById('i1').style.height = height + "px";  //modify height
    } else {
        clearInterval(myVar)
    }
//css
#i1 {
  width: 100px;
  display: inline-block;
  background:red;
  position: absolute;
  top: 150px;  //initial top
  bottom: 250px;  //as as bottom of #i
  height:100px;  //initial height

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM