自动打开<详细信息> ID号码上的元素 [英] Automatically open <details> element on ID call

查看:97
本文介绍了自动打开<详细信息> ID号码上的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我的HTML源代码:

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

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

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

如果调用example.com/page.html#sample-slug,我该如何提供详细信息元素意识到这一点,并添加打开属性?我想确保在调用锚点时内容可见。

解决方案

我不认为您可以打开< details> 单独使用CSS。但是,您可以:


  1. 使用 location.hash 获取散列。可能收听 hashchange 事件。

  2. 使用 document.getElementById 元素。

  3. 设置其打开属性为true。

  function openTarget(){var hash = location.hash.substring(1); if(hash)var details = document.getElementById(hash); if(details&& detail.tagName.toLowerCase()==='details')details.open = true;} window.addEventListener('hashchange',openTarget); openTarget();  :target {background:rgba(255,255,200,.7);} 

< details id =foo>详情<摘要>摘要< / summary>< / details>< div>< a href =#foo>#foo< / a> < a href =#bar>#bar< / a>< / div>

$ b

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.

解决方案

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>

这篇关于自动打开&lt;详细信息&gt; ID号码上的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆