2017-05-31 70 views
0

在網站的一個頁面上有選項卡,每個選項卡都有自己的ID,因此您可以通過make http://www.example.com/page#tab1直接呼叫每個選項卡。我可以有兩個處理程序的網址?

的問題是,我想要的網址,將打開的選項卡未開始時,但具體內容是在內容的途中,也有ID,因爲是下拉。

我可以做萬聯科將打開特定的標籤,但也將滾動到其它ID或至少例如將prescrool 200像素?

回答

1

我不是很有經驗,但我看到你的問題,我很好奇這是否可以完成和如何。

如果我有這個權利,你有元素#TAB1#TAB2等,並希望能夠指向內他們一定的元素。像#tab1>#element1,#tab1>#element2等。您也已經實現了一個與URL一起工作的選項卡系統。 更多關於你爲什麼需要這樣做的內容以及什麼情況會對老實說非常有用,但我會給你我最好的照片。

第一件事,我能想到的(和我有想法,如果這是一個很好的做法與否)將是檢查和保存散列一個網址,並使用和相應地使用scrollTop的方法。

不管怎樣,我把使用jQuery做這個https://codepen.io/cssjockey/pen/jGzuK簡單的標籤系統,我試圖使其與網址兩個散列工作。

爲此,我不得不從codepen下載代碼,並將一個index.html文件放在一起以嘗試這一點,因爲我不知道如何使用codepen處理URL上的哈希值。

我所要做的只是稍微調整JS並在選項卡中添加更多元素,以便頁面轉到某個錨點時會很明顯。這裏是我的更新JS這裏:

$('ul.tabs li').click(function(){ //this simply make the tab system work. It's from the codepen. 
    var tab_id = $(this).attr('data-tab'); 

    $('ul.tabs li').removeClass('current'); 
    $('.tab-content').removeClass('current'); 

    $(this).addClass('current'); 
    $("#"+tab_id).addClass('current'); 
}) 

if(document.location.hash) { //now let's check if there's a hash 
     var u = window.location.hash.substring(1);; //And if so let's puts hash in variable 
     hash = u.split('#'); //split it by # character and save it as an array 

     var element = jQuery('#'+hash[0]); //now let's set that first hash as current tab 
     $('.tab-content').removeClass('current'); //but first remove the curent classes first 
     $('.tab-link').removeClass('current');   
     element.addClass('current'); 
     $("[data-tab="+hash[0]+"]").addClass('current'); //done selecting the tab using hash from URL 

     if(hash[1]) { // now! if there's another hash in the URL 
     var subElement = $('#'+hashes[1]); 
     var goToElement = subElement.offset().top; 

     $(window).scrollTop(goToElement);//go there! 
     }   

現在,如果我嘗試accesing /index.html#tab-4#element它帶我到一個在第4片的底部。

它不知道你在哪裏或者什麼你就大功告成了,仍然需要工作一個超級粗略的想法。如果你能提供一些幫助你的代碼會更容易。

0

我不會在散列中結合多個ID,而是會搜索具有由URL散列定義的id的元素,然後使用例如DOM遍歷DOM。 .closest('.tab-element'),直到到達DOM的根目錄爲止,檢查是否需要切換一個或多個選項卡,切換到這些選項卡,然後將該元素滾動到屏幕的可見部分。

解決這個問題會讓你的代碼更容易維護,因爲你不需要關心元素是如何嵌套的。

你如何做到這一點完全取決於你如何實現你的選項卡。

相關問題