2016-02-04 64 views
1

我有一些圖像選項卡式的內容,它的效果很好。但是,在小屏幕上,標籤垂直疊放而不是水平對齊。這意味着在手機上人們不知道向下滾動以查看內容。jquery滾動到點擊頁面部分間歇工作

我試圖讓它工作,所以當選中標籤時,它們會自動滾動到標籤內容的頂部,以便標籤內容的標題顯示在屏幕的頂部。我有以下代碼,但它似乎間歇性地工作。有誰知道我做錯了什麼? (https://jsfiddle.net/v5p625qb

// Tabbed Content 
$(".tabbed-content-tab").click(function(evt) { 
    evt.preventDefault(); 
    $('html,body').animate({ 
     scrollTop: $(".hero-title").offset().top 
    }); 

    $(".tabbed-content").removeClass("show"); 

    var classIdentifier = this.className.match(/content\d/); 

    $(".tabbed-content." + classIdentifier).addClass("show"); 
}); 

//$(".tabbed-content-tab").first().click(); 
$(".tabbed-content.content1").addClass("show"); 

<div class="tabbed-content-tab button content1 col-sm-2"> 
<div class="pad-box"><img class="aligncenter" src="/wp-content/uploads/2016/01/75675.png" alt="" /> 
<strong>Image tab 1</strong></div> 
</div> 

<div class="tabbed-content-tab button content2 col-sm-2"> 
<div class="pad-box"><img class="aligncenter" src="/wp-content/uploads/2016/01/7567.png" alt="" /> 
<strong>Image tab 2</strong></div> 
</div> 

<div class="tabbed-content-tab button content3 col-sm-2"> 
<div class="pad-box"><img class="aligncenter" src="/wp-content/uploads/2016/01/36556.png" alt="" /> 
<strong>Image tab 3</strong></div> 
</div> 

<div class="tabbed-content-tab button content4 col-sm-2"> 
<div class="pad-box"><img class="aligncenter" src="/wp-content/uploads/2016/01/3232.png" alt="" /> 
<strong>image tab 4</strong></div> 
</div> 

<div class="tabbed-content content1"> 
    <h2 class="hero-title">tab 1 content</h2> 
lorem ipsum 
<iframe src="https://player.vimeo.com/video/5345" width="768" height="432" frameborder="0" allowfullscreen="allowfullscreen"></iframe> 

</div> 

<div class="tabbed-content content2"> 
    <h2 class="hero-title">tab 2 content</h2> 
lorem ipsum 
<iframe src="https://player.vimeo.com/video/3343" width="768" height="432" frameborder="0" allowfullscreen="allowfullscreen"></iframe> 

</div> 

<div class="tabbed-content content3"> 
    <h2 class="hero-title">tab 3 content</h2> 
lorem ipsum 
<iframe src="https://player.vimeo.com/video/3343" width="768" height="432" frameborder="0" allowfullscreen="allowfullscreen"></iframe> 

</div> 


<div class="tabbed-content content4"> 
    <h2 class="hero-title">tab 4 content</h2> 
lorem ipsum 
<iframe src="https://player.vimeo.com/video/3343" width="768" height="432" frameborder="0" allowfullscreen="allowfullscreen"></iframe> 

</div> 

回答

0

這裏是the fiddle的更新版本。

我改變了這一行:

scrollTop: $(".hero-title").offset().top 

找到.hero-title你真的想滾動,而不是全部。

此外,隱藏和顯示必須發生在我們讀取偏移之前,因爲它依賴於元素的可見性。

http://api.jquery.com/offset/

注:jQuery的不支持獲取隱藏 元素的偏移座標......選擇了第一個選項卡時

你的版本中都能正常工作,你點擊一些選項卡。這是因爲offset獲取了匹配元素集中第一個元素的偏移量,並且在隱藏當前打開的選項卡之前讀取了偏移量。當其他選項卡打開時,將獲得0作爲偏移量。