在ID调用上自动打开<details>元素

时间:2016-05-04 16:35:27

标签: html css html5 details

我试图在ID调用包含时自动打开元素,例如:http://www.example.com/page.html#container。理想情况下,我希望滚动到所在页面的位置(在摘要元素内),然后打开details元素。显然,本机滚动功能工作正常,但如何设置要打开的details元素呢?

这是我的HTML源代码:

<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>

当调用example.com/page.html#sample-slug时,如何让detail元素知道并添加&#34; open&#34;属性?我想确保在调用锚点时内容是可见的。

2 个答案:

答案 0 :(得分:4)

我不认为你可以单独用CSS打开.inputBoxA .tt-menu 。但你可以:

  1. 使用<details>获取哈希值。可能会收听location.hash事件。
  2. 使用hashchange获取元素。
  3. 将其document.getElementById属性设置为true。
  4. &#13;
    &#13;
    open
    &#13;
    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();
    &#13;
    :target {
      background: rgba(255, 255, 200, .7);
    }
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

下面,我提供适用于嵌套 <details><summary>元素的解决方案:

借助javascript,您可以:

  • 跟踪URL中哈希锚的变化
  • 通过相应地更改detail元素的open属性来对其进行反应

下面是执行此操作的示例,在此处编写代码→https://stackoverflow.com/a/55377750/544721

details html element changing screencast