Automatically open
element on ID call

前端 未结 2 654
孤街浪徒
孤街浪徒 2020-12-21 04:44

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

相关标签:
2条回答
  • 2020-12-21 05:20

    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>

    0 讨论(0)
  • 2020-12-21 05:32

    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

    0 讨论(0)
提交回复
热议问题