2012-08-05 66 views
6

在我的主頁底部,我已經包含了一個聯繫表單,併爲本節指定了div id =「contact」。鏈接到不同的頁面 - > jquery滾動到特定的錨點

當任何頁面上的聯繫人按鈕被點擊時,它應該導航到主頁和頁面加載,自動滾動到聯繫表格。

我在檢查了一個類似的問題之後,在找到這裏之後,我一直沒有成功:jQuery scroll to ID from different page當我嘗試時,它只是跳到表單。我想讓它順利滾動。

<li><span>Get in touch</span><a href="index.html#contact">Contact</a></li> 

問題jQuery函數滾動到接觸錨從其他網頁主頁上:

(function($){ 
    var jump=function(e) { 
     if (e) { 
      e.preventDefault(); 
      var target = $(this).attr("href"); 
     } else { 
      var target = location.hash; 
     } 

     $('html,body').animate({ 
      scrollTop: $(target).offset().top 
     },1000,function() { 
      location.hash = target; 
     }); 
    } 

    $('html, body').hide() 

    $(document).ready(function() { 
     $('a[href^=#]').bind("click", jump); 

    if (location.hash) { 
     setTimeout(function(){ 
      $('html, body').scrollTop(0).show() 
      jump() 
     }, 0); 
    } else { 
     $('html, body').show() 
    } 
}); 

我想實現類似於此示例東西:http://vostrel.cz/so/9652944/page.html區別在於,代替在這種情況下出現在這兩個頁面上的「錨點ID」,錨點ID(聯繫人)對我來說只出現在一頁(家庭)上。

回答

0

我不確定你的代碼是什麼,但我已經能夠得到它的工作。有一件事是,你發佈的代碼,最後缺少})(jQuery)。無論如何,看看我做了什麼here,我想這就是你要找的。我不確定你的網站的HTML是什麼樣的,但我認爲你可以適應它。您只需將聯繫人按鈕的href屬性設置爲index.html#contact即可。在index.html上,你可以使用#contact,它會做同樣的事情。

index.html中,部首:

<div id="header"> 
    <a href="index.html">Homepage</a> 
    <a href="otherpage.html">Other page</a> 
    <a href="otherpage2.html">Another Page</a> 
    <a href="#contact">Contact</a> 
</div> 

但在任何其他頁面:

<div id="header"> 
    <a href="index.html">Homepage</a> 
    <a href="otherpage.html">Other page</a> 
    <a href="otherpage2.html">Another Page</a> 
    <a href="index.html#contact">Contact</a> 
</div> 

在index.html中的頭部移除index.html防止頁面被加載兩次,以便jQuery只是向下滾動頁面。

0

小技巧中,我遇到了同時檢測出你的代碼:

因爲你使用的錨標記的href屬性,它過來的#contact,其中jQuery的解釋爲一個ID。

無論頁面處於何種狀態,您都需要向錨點添加一個id =「contact」以使其工作。

1

試試這個,你的劇本是隻確定最後一行缺少

(function ($) { 

    var jump = function (e) { 
     if (e) { 

      e.preventDefault(); 
      var target = $(this).attr("href"); 

     } else { 

      var target = location.hash; 

     } 
     $('html,body').animate({ 

      scrollTop: $(target).offset().top 

     }, 1000, function() { 

      location.hash = target; 

     }); 
    } 

    $('html, body').hide(); 

    $(document).ready(function() { 
     $('a[href^=#]').bind("click", jump); 

     if (location.hash) { 
      setTimeout(function() { 

       $('html, body').scrollTop(0).show() 
       jump(); 

      }, 0); 
     } else { 

      $('html, body').show(); 

     } 
    }); 
})(jQuery) 
相關問題