简体   繁体   English

在javascript中使用if/else更改图像或背景ID大小

[英]Using if / else to change image or background id size in javascript

I am just getting into Javascript and I am trying to modify mode code using if / else statements.我刚刚进入 Javascript,我正在尝试使用 if / else 语句修改模式代码。 The original code is:原代码是:

document.getElementById("button1").addEventListener("click", function(){    
    document.getElementById("box").style.height= "250px";    
});

I tried modifying it several ways and researched as much as I could but even after many trial and error attempts I just cant figure out how to do it.我尝试通过多种方式修改它并尽可能多地进行研究,但即使经过多次反复试验,我也无法弄清楚如何去做。 So far the code I have come up with that makes the most sense to me is到目前为止,我提出的对我来说最有意义的代码是

if(document.getElementById("button1").clicked == true) {    
    document.getElementById("box").style.height = "250px";    
};

but that does nothing.但这没有任何作用。 Any input would be much appreciated.任何输入将不胜感激。 Thank you.谢谢你。

there you go你去吧

 buttons = document.querySelectorAll(".button"); i = 0, length = buttons.length; for (i; i < length; i++) { if (document.addEventListener) { buttons[i].addEventListener("click", function() { handleOnClick(this.id); }); } }; function handleOnClick(button_id) { switch(button_id) { case "button1" : document.getElementById("box").style.height = "250px"; break; case "button2" : document.getElementById("box").style.height = "100px"; break; default: //whatever not needed break; } }
 .boxclass { width:100px; height:100px; background:red; }
 <div id="my-buttons"> <button id="button1" class="button">Change To 250</button> <button id="button2" class="button">Change to 100</button> </div> <br/> <div id="box" class="boxclass"></div>

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

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