简体   繁体   中英

(JavaScript / HTML) How to change display in style attribute on button click?

I'm a beginner programmer and I wanted to have an image loaded but not displayed:

<img src="someImage.png" class="mainImage" id="image1" style="display:none"/>

I want to add a button which would then remove/change the image display from none to make it visible, so that each image could be displayed by clicking on a button.

Thanks!

You can toggle the element's display between block and "" (empty string). So you might have a button like:

<button onclick="toggleDisplay('image1')">Image 1</button>

And a toggleDisplay function like:

function toggleDisplay(id) { 
  var el = document.getElementById(id);
  if (el && el.style) {
    el.style.display = el.style.display != 'none'? 'none' : '';
  } 
}

Toggling between none and "" (empty string) allows the element to return to its default or inherited value and the function becomes generic.

Try this

$("#btn").click(function(){
    $("#image1").show();
});

Or

$("#btn").click(function(){
     $("#image1").css("display", "block");
 });

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