gpt4 book ai didi

javascript - 滚动到点击/打开的 div 并偏移之前打开的 div

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:01 26 4
gpt4 key购买 nike

我在这里遇到的问题是如何滚动到另一个关闭时单击的 div 的顶部。如果没有打开的 div,我可以让它工作,但如果打开了,它就无法滚动到新打开的 div 的顶部。我假设我需要用旧的开放 div 来抵消。虽然不确定如何去做。这是便于引用的 fiddle - http://jsfiddle.net/dnym5p1s/3/

缩短代码:HTML:

<div class="option-heading">
<h1>Year1 <span class="arrow-up">&#9650;</span><span class="arrow-down">&#9660;</span></h1>
</div>
<div class="option-content">ContentContentContent <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content</div>

<div class="option-heading">
<h1>Year2 <span class="arrow-up">&#9650;</span><span class="arrow-down">&#9660;</span></h1>
</div>
<div class="option-content">Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />vContent <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br />Content <br /></div>

CSS:

.option-heading h1 {
margin:0;
padding:8px 5px;
font-size:19px
}
.option-content h4 {
color: #900027;
font-weight: bold;
margin:25px 0 0
}
.option-content p {
margin-top:0
}
.option-content {
border-bottom: 10px solid #800202;
border-top: 10px solid #800202;
}
.arrow-up,.arrow-down{color:#647f8a;cursor:pointer;width:20px; font-size:10px; padding:0 0 0 10px;vertical-align:middle}

jQuery:

$('.option-content,.arrow-up, .arrow-down:first').hide();
$('.option-content:first,.arrow-up:first').show();
$('.option-heading').click(function () {
$('.option-content').not($(this).next()).slideUp(250);
$('.option-heading').not(this).find('span.arrow-up').hide();
$('.option-heading').not(this).find('span.arrow-down').show();
$(this).next('.option-content').slideToggle(250);
$(this).find('.arrow-up, .arrow-down').toggle();
//Jump to Open Div
$('html,body').animate({scrollTop: $(this).offset().top - 10}, 'fast');
});

最佳答案

隐藏内容后,存储每个option-heading的顶部偏移量:

$('.option-content,.arrow-up, .arrow-down:first').hide();

$('.option-heading').each(function() {
$(this).data('top', $(this).offset().top - 10);
});

然后您可以将 scrollTop 动画化到该位置:

$('html,body').animate({scrollTop: $(this).data('top')}, 'fast');    

Working Fiddle

关于javascript - 滚动到点击/打开的 div 并偏移之前打开的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28706319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com