2015-04-16 152 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