[英]Scroll to clicked/open div and offset by previously opened div
我這里的問題是如何滾動到另一個關閉時單擊的div的頂部。 如果沒有打開div,我可以使其工作,但是如果沒有打開,則無法滾動到新打開的div的頂部。 我假設我需要抵消舊的開放div。 雖然不確定如何去做。 這是供您參考的小提琴-http: //jsfiddle.net/dnym5p1s/3/
縮短的代碼:HTML:
<div class="option-heading">
<h1>Year1 <span class="arrow-up">▲</span><span class="arrow-down">▼</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">▲</span><span class="arrow-down">▼</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');
});
問題不在於您必須抵消舊的open div:這僅是一個問題,如果舊的open div在新的div之上,這意味着新div的相對位置在動畫過程中發生變化。 (如果舊的div在新的div之下,則新的div的位置在動畫過程中不會更改。)
為了解決這個問題,您需要將動畫排入隊列 ,以便在舊div關閉后進行滾動。
隱藏內容后,存儲每個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');
我的方法是給標題加上一個ID
<h1 id="4">Year4 ....
並使用loaction屬性導航到
yoururl.com/index.html#4
就像一個魅力..也許不是在jsfiddle艱難
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.