简体   繁体   中英

How to expand nested HTML5 <details> elements to make a link target visible?

I have a html5 page which contains something like this:

<details>
  <summary>X and Y</summary>
  <details id="x">
    <summary>X</summary>
    Long text about x.
  </details>
  <details id="y">
    <summary>Y</summary>
    Long text about Y.
  </details>
</details>
A lot of other stuff.
<a href="#x>Go to X</a>
<a href="#y>Go to Y</a>

I already use a CSS details:target spec to highlight the link target when a user clicks on one of the "Go to X/Y" links. However, if the top-level details-element is not expanded, the user can't see it and it seems like it wouldn't work.

So is there a way (preferably only html5 + css) to expand the top-level details-element when a link targeting some of its children is clicked?

The only way for now is using Javascript. You can read this for already written code: http://www.sitepoint.com/fixing-the-details-element/

I wrote this code

 <script> function openDetailsNested() { var listOpen = document.querySelectorAll("details[open]"); if(listOpen.length > 0) { for(var i=0; i<listOpen.length; i++) { var elem = listOpen[i]; while (elem) { if (elem.matches("DETAILS")) { elem.setAttribute("open",""); } elem = elem.parentElement; } } } } window.addEventListener("load", openDetailsNested,true); </script>

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