展开详细信息/摘要时滚动到锚点?

时间:2018-01-14 23:57:51

标签: javascript jquery html css

我有一大堆叠加的div,其中包含id个标记包含details个锚点和嵌入的视频。是否可以同时展开summary并滚动到其details一次点击?如果我使用下面的脚本,我可以滚动到包含id标记的锚点:

a

但是,将/* JS */ $(document).ready(function(){ $('a[href^="#"]').on('click',function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 400, 'swing', function () { window.location.hash = target; }); }); }); /* HTML */ <div id="anchor></div> <a href="#anchor">Scroll to anchor</a> summary本身包裹在details标记中会禁用此滚动效果。

a

我尝试了很多不同的版本,但我似乎无法获得展开+滚动的综合效果。什么是解决这个问题的正确方法?

1 个答案:

答案 0 :(得分:1)

好吧,details标记使用open属性进行展开,因此您只需在点击触发时添加此属性。

$('details').attr('open', true);

如果要关闭它,请使用:

$('details').attr('open', false);

在您的代码中,最好使用此选择器:

$(target + ' details').attr('open', true);

$(document).ready(function() {
  $('a[href^="#"]').on('click', function(e) {
    e.preventDefault();
    var target = this.hash,
      $target = $(target);
      $(target + ' details').attr('open', true);
    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 400, 'swing', function() {
      window.location.hash = target;
    });

  });
});
#divide {
height: 500px;
}

body {
  padding-bottom: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#anchor1">Scroll to anchor</a>
<br>
<a href="#anchor2">Scroll to anchor</a>
<br>
<a href="#anchor3">Scroll to anchor</a>
<br>
<a href="#anchor4">Scroll to anchor</a>

<div id="divide"></div>

<div id="anchor1">
    <details><a href="#anchor1"><summary>Embedded Video</summary></a>
        <div class="youtube-player" data-id="null"></div>
    </details>
</div>

<div id="anchor2">
    <details><a href="#anchor2"><summary>Embedded Video</summary></a>
        <div class="youtube-player" data-id="null"></div>
    </details>
</div>

<div id="anchor3">
    <details><a href="#anchor3"><summary>Embedded Video</summary></a>
        <div class="youtube-player" data-id="null"></div>
    </details>
</div>

<div id="anchor4">
    <details><a href="#anchor4"><summary>Embedded Video</summary></a>
        <div class="youtube-player" data-id="null"></div>
    </details>
</div>