2015-04-16 249 views
0

我試圖做一個錨點鏈接,當你點擊它滾動到另一個元素。我曾嘗試與前一個問題的答案,這樣做:Smooth scrolling when clicking an anchor link使用此代碼從它HTML錨鏈接平滑滾動

$('a[href*=#]').click(function(event){ 
$('html, body').animate({ 
    scrollTop: $($.attr(this, 'href')).offset().top 
}, 500); 
event.preventDefault(); 
}); 

當我使用此代碼與此HTML

<a id="des" href="#scroll"> 
<img name="scroll" id="scroll" src="whatever"> 

它不平滑滾動,而是瞬間跳到這裏。它也沒有跳到正確的地方。它在圖像下跳轉,以至於看不到圖像。

我在做什麼:我試圖讓它這樣,當我點擊這個錨點元素時,它平滑地滾動到這個圖像而不切斷它。我的意思是當我現在做它跳過圖像。

回答

3

這將做你想做的。它來自StackOverFlow的某個人。我不記得哪個用戶。

$(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 
     }, 800); 
     return false; 
     } 
    } 
    }); 
}); 

編輯: 另外這是我做的,如果有在頂部有固定的導航。這將抵消您的導航的金額。

在CSS

a.anchor { 
     display: block; 
     position: relative; 
     top: -45px; //or what ever the set px amount you have set to your nav 
     visibility: hidden; 
} 

,並使用此錨標記就在您的圖像標籤

<a class="anchor" id="WhateverYourHerfIs"></a> 
+0

是的,這個平穩滾動之前,但仍跳過圖像。我應該爲分配器元素製作頭像,還是將圖片放在圖片上方? – JarFile

+0

你應該把圖像放在一個div中,讓它錨定在div而不是圖像上還有一個固定的導航欄在頂部嗎?有一個px高度? – Darkrum

+0

哦,我看到了問題,是的,我確實有一個固定的導航欄頂部設置像素高度n的東西。這可能阻礙了這一觀點。所以這是圖像,但它阻止了它。我應該在哪裏發送滾動到那裏去?在圖像上方有幾個像素? – JarFile