简体   繁体   中英

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. 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>

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