简体   繁体   中英

Javascript: Show/hide toggle first click not working

I am working on a page, and got this annoying issue. The page has 10 figures, and the figcaptions are set to display:none as default. The effect I want is for a click on any image to show its respective caption, and hide any other captions. Overall, it works well, but the first click on an image doesn't do anything.

Any ideas on what I might be doing wrong?

function toggle(figureNum){
  var captions = document.getElementsByTagName("FIGCAPTION");

  if (captions[figureNum].style.display == "none"){
    for (i = 0; i < 10; i++){
      captions[i].style.display = "none";
    }
    captions[figureNum].style.display = "block";
  } else {
    captions[figureNum].style.display = "none";
  }
}

Thanks!

There's no display property set within the element's style property to begin with( ele.style.display ). This means that it's an empty string, not "none"

 let caption = document.createElement("figcaption"); document.body.appendChild(caption); console.log("display equals " + caption.style.display); 

This does not mean that, if you have it set as display: none within your CSS that you cannot retrieve that value.

You can use getComputedStyle(ele).getPropertyValue("display") to pull the actual display styling applied by CSS whereas the styling within the element itself( ele.style ) may not accurately reflect the properties set within CSS styling.

  let caption = document.createElement("figcaption"); document.body.appendChild(caption); console.log("display equals " + getComputedStyle(caption).getPropertyValue("display")); 
 figcaption { display: none; } 

In the end you can simply adjust your code to allow for the one-off eventuality of the display property on the element being an empty string, or you could pull the value directly from your CSS and compare that instead:

 function toggle(figureNum){ var captions = document.getElementsByTagName("FIGCAPTION"), displayProp = getComputedStyle(captions[figureNum]).getPropertyValue("display"); if (displayProp == "none"){ for (i = 0; i < captions.length; i++){ captions[i].style.display = "none"; } captions[figureNum].style.display = "block"; } else { captions[figureNum].style.display = "none"; } } document.querySelector("img").addEventListener("click", (e) => { toggle(0); }); console.log(document.querySelector("figcaption").style.display); 
 FIGCAPTION { display: none; } 
 <img src="http://via.placeholder.com/350x150"> <FIGCAPTION>BLAH BLAH BLAH</FIGCAPTION> 

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