Automatically open
element on ID call

前端 未结 2 655
孤街浪徒
孤街浪徒 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

    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 Summary

提交回复
热议问题