Automatically open <details> element on ID call

馋奶兔 提交于 2020-02-12 03:43:26

问题


I'm trying to automatically open a element when a containing is called by ID, for example: http://www.example.com/page.html#container. Ideally I'd like this to scroll to the point of the page where the is located (inside the summary element), and then open the details element. Obviously, the native scroll function works fine, but how can I set the details element to open?

Here's my HTML source:

<details class="concentration">
   <summary>
        <h4 id="sample-slug"><?php the_sub_field('emphasis_name'); ?></h4>
    </summary>

    <p><?php the_sub_field('emphasis_description'); ?></p>

    <div class="courses"><?php the_sub_field('emphasis_course_list'); ?></div>
</details>

When example.com/page.html#sample-slug is called, how can I make the details element aware of that and add the "open" attribute? I want to make sure the content is visible when the anchor is called.


回答1:


I don't think you can open <details> with CSS alone. But you can:

  1. Get the hash with location.hash. Possibly listen to hashchange event.
  2. Use document.getElementById to get the element.
  3. Set its open property to true.

function openTarget() {
  var hash = location.hash.substring(1);
  if(hash) var details = document.getElementById(hash);
  if(details && details.tagName.toLowerCase() === 'details') details.open = true;
}
window.addEventListener('hashchange', openTarget);
openTarget();
:target {
  background: rgba(255, 255, 200, .7);
}
<details id="foo">Details <summary>Summary</summary></details>
<div><a href="#foo">#foo</a> <a href="#bar">#bar</a></div>



回答2:


Below I provide solution that works for nested <details><summary> elements:

With help of javascript you can:

  • track changes of hash anchor in url
  • react to them by changing open attribute of details elements accordingly

Here is example that does it, code here → https://stackoverflow.com/a/55377750/544721



来源:https://stackoverflow.com/questions/37033406/automatically-open-details-element-on-id-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!