繁体   English   中英

基本的javascript用户输入更改div

[英]Basic javascript user-input changing div

我正在尝试使用带有for循环和if-else语句的用户输入来更改框的宽度。 似乎无法获得第一个if语句来执行。 这是javascript:

function changeWidth(){
    var widthSize = document.getElementById("num").value;
    for(var s = 0; s < widthSize; s++){
        if(s < 0 || s > 800){
            alert("Not a valid width size"); }
        else {
            document.getElementById("box-1").style.width="s";
        }
    }
}

CSS:

.box {
    border: 1px solid black; 
    width: 200px; 
    height: 200px; 
    float:left; 
    margin-left:30px;
}

HTML:

<input type="number" id="num" name="num" value="" placeholder="Please enter width size" />
<input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" />
<div class="box" id="box-1"></div>

你不需要循环,这应该这样做。

function changeWidth(){
    var widthSize=document.getElementById("num").value;
    if(widthSize < 0 || widthSize > 800){
        alert("Not a valid width size"); }
    else {
        document.getElementById("box-1").style.width=widthSize+"px";
    }
}

如果您尝试多次更改宽度,那么您只需要删除变量s的引号。

像这样:

document.getElementById("box-1").style.width=s;

但是如果你试图设置widthSize的值,而只是一次,它可能是这样的:

document.getElementById("box-1").style.width=widthSize;
return;

这应该工作......

 function changeWidth() { var widthSize = parseInt(document.getElementById("num").value); if (widthSize < 0 || widthSize > 800) { alert("Not a valid width size"); } else { document.getElementById("box-1").style.width = widthSize + 'px'; } } 
 .box { border: 1px solid black; width: 200px; height: 200px; float: left; margin-left: 30px; transition: width 1s ease; } 
 <input type="number" id="num" name="num" value="" placeholder="Please enter width size" /> <input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" /> <div class="box" id="box-1"> <div class="box-1-words" id="b1-words"> Hello World </div> </div> 

s永远不会小于0,因为你的for循环的最小值,如果数字u输入小于800,则IF条件永远不会执行。 您输入的数字是否超过800且仍未显示警报?

 function changeWidth(){ var widthSize=document.getElementById("num").value; for(var s=0;s<widthSize;s++){ if(widthSize<0 || widthSize>800){ alert("Not a valid width size"); break; } else{ var a ="transition:2s ease-in;width:"+widthSize+"px;" document.getElementById("box-1").style.cssText=a; } } } 
 .box{border:1px solid black; width:200px; height:200px; float:left; margin-left:30px;} 
 <input type="number" id="num" name="num" value="" placeholder="Please enter width size" /> <input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" /> <div class="box" id="box-1"></div> </body> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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