2014-05-04 126 views
0

我在每個頁面中都有一個菜單欄,當我點擊其中一個子項目時,我希望頁面重定向到另一個html並順利滾動到該特定DIV。 我使用這個代碼把它一個頁面的div內順利滾動:平滑滾動到不同的HTML頁面中的div

$(function() { 
    $('a[href*=#]:not([href=#])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 

     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html,body').animate({ 
      scrollTop: target.offset().top 
     }, 1000); 
     return false; 
     } 
    } 
    }); 
}); 

有沒有讓我能有什麼,我要求修改這個代碼的方法嗎?

+0

我認爲你需要保存滾動到無論是在PHP會話什麼格,或者如果您在新的頁面URL添加DIV ID和使用JavaScript得到它,所以你知道在哪裏滾動到。 – Medda86

回答

0

使用錨標記和這樣的:

$(function() { 
    $('a[href*=#]:not([href=#])').click(function() { 
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html,body').animate({ 
      scrollTop: target.offset().top 
     }, 1000); 
    return false; 
    } 
} 
}); 
}); 

看到這一點:查看源代碼:http://css-tricks.com/examples/SmoothPageScroll/

我發現simething用於捕捉頁面

var match = location.hash.match(/^#?(.*)$/)[1]; 
if (match) 
{ 
    //call you smooth scroll code. Fake the link click etc 
} 
+0

是的,但這隻適用於單頁網站。當我點擊其中一個子菜單項時,我希望能夠有很多頁面,並且仍然能夠獲得平滑的效果。喜歡這個網站:http://www.creadevsolutions.com/Home。轉到服務,然後單擊任何項​​目。 – user3602426

+0

您可以使用JavaScript從網址獲取錨點,然後執行相同的代碼進行平滑滾動。 (我需要更多關注OP發佈的代碼) –

+0

var type = window.location.hash.substr(1); –

0

在尋找解決的辦法,通過谷歌和stackoverflow,以處理平滑滾動到錨點很顯然,許多相同頁面的解決方案存在。處理跨多個頁面的多個錨點之間的平滑滾動似乎僅限於在stackoverflow上的一個QA。然而,這個解決方案並不適合我。

雖然我剛剛處理初學者處理java和CSS,但我想通過將幾種解決方案合併到一個至少適用於Firefox和Chrome(未在其他瀏覽器上測試)的解決方案來傳遞解決方案。

我希望有人可以看看這一點,並提出一些建議: 1)使其更跨瀏覽器兼容 2)把它清理乾淨

最後,這裏有一些條件我的有它的工作沒有問題:

多頁 - 多個錨 引導3個 多個jQuery函數

上有警告,雖然我已經在這裏張貼着關於磚石和多個錨定跨頁:Anchors to pages with Masonry layouts

$(function() { 
    $('[data-toggle="elementscroll"]').click(function() { 
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
       && location.hostname == this.hostname) { 

      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
      if (target.length) { 
       $('html,body').animate({ 
        scrollTop: target.offset().top -57 //head space 
       }, 1000); //scroll speed 
       return false; 
      } 
     } 
    }); 
}); 

    $(function() { 
$('html, body').hide(); 
if (window.location.hash) { 
     setTimeout(function() { 
       $('html, body').scrollTop(0).show(); 
       $('html, body').animate({ 
         scrollTop: $(window.location.hash).offset().top -57 // head space 
         }, 1000) //scrollspeed 
     }, 0); 
} 
else { 
     $('html, body').show(); 
} 
    });