繁体   English   中英

HTML锚链接平滑滚动

[英]HTML Anchor link smooth scrolling

我试图做一个锚点链接,当您单击它时,向下滚动到另一个元素。 我尝试使用上一个问题的答案进行此操作: 单击锚定链接时平滑滚动使用此代码

$('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">

它不会使滚动平滑,而是会立即跳到此处。 它也不会跳到正确的位置。 它会跳到图像下方,因此您看不到图像。

我想做的事情:我想拥有它,所以当我单击该锚点元素时,它会平滑滚动到该图像而不会被剪切掉。 我的意思是当我现在这样做时,它会跳过图像。

这将做您想要的。 它来自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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM