我有一大堆叠加的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
我尝试了很多不同的版本,但我似乎无法获得展开+滚动的综合效果。什么是解决这个问题的正确方法?
答案 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>