我有一大堆堆叠的 div,其中包含 id
anchor 和包裹在 details
和 summary
标签中的嵌入视频。是否可以通过单击同时展开详细信息
并滚动到其id
?如果我使用下面的脚本,我可以滚动到带有 a
标记的 anchor :
/* 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
标记中将禁用此滚动效果。
/* HTML */
<div id="anchor">
<details><a href="#anchor"><summary>Embedded Video</summary></a>
<div class="youtube-player" data-id="null"></div>
</details>
</div>
我尝试了许多不同的变体,但我似乎无法获得展开+滚动的组合效果。解决这个问题的正确方法是什么?
最佳答案
嗯,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>
关于javascript - 展开详细信息/摘要时滚动到 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255385/