如何锚定HTML详细信息中的目标元素

时间:2018-01-04 17:25:33

标签: html html5 anchor

摘要元素关闭时,它不会滚动到顶部。有没有办法让它自动扩展或什么?

这是我的意思的一个例子:

<details>
  <summary>Header</summary>
  <div id=anchored>
  Should anchor here.
  </div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>

2 个答案:

答案 0 :(得分:3)

我认为可以实现的唯一方法是使用JS

  • 在锚元素上单击,找到它的目标DIV,
  • 找到.closest() details并点击它的summary元素。
  • 仅当 targetDIV 不可见时才执行上述所有操作(详细信息已关闭)。

&#13;
&#13;
$("[href^='#']").on("click", function() {
  var $targetDIV = $(this.getAttribute("href"));
  if ($targetDIV.is(":hidden")) {
    $targetDIV.closest("details").prop("open", true);
  }
});
&#13;
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details>
  <summary>Header</summary>
  <div id=anchored>Should anchor here.</div>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

没有jQuery

使用纯JS(ES6),它看起来像:

&#13;
&#13;
const openDetailsIfAnchorHidden = evt => {
  const targetDIV = document.querySelector(evt.target.getAttribute("href"));
  if ( !! targetDIV.offsetHeight || targetDIV.getClientRects().length ) return;
  targetDIV.closest("details").open = true;
}


[...document.querySelectorAll("[href^='#']")].forEach( 
   el => el.addEventListener("click", openDetailsIfAnchorHidden )
);
&#13;
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details>
  <summary>Header</summary>
  <div id=anchored>Should anchor here.</div>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您有每个细节的ID。如果您有多个相互封闭,这将有效。很多信用@Roko C. Buljan

&#13;
&#13;
const openDetailsIfAnchorHidden = (evt) => {
  const el = evt.target;
  let details = document.querySelector(el.getAttribute("href"));
  if ( !!details.offsetHeight || details.getClientRects().length ) return;
  while (details != null)
  {
      details = details.closest("details:not(#" + details.id +
      ")");
      if (details == null)
        return;
      const summary = details.querySelector("summary");
      details.setAttribute('open', '');
  }
}


[...document.querySelectorAll("[href^='#']")].forEach( 
   el => el.addEventListener("click", openDetailsIfAnchorHidden )
);
&#13;
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details id=d1>
  <summary>Header</summary>
  <details id=d2><summary>Header 2</summary><div id=anchored>Should anchor here.</div></details>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>
&#13;
&#13;
&#13;