平滑滚动锚点jQuery [英] Smooth scroll anchor jquery

查看:83
本文介绍了平滑滚动锚点jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用锚URL创建导航并平滑滚动. 但是在该页面上,我使用了一个高度为88px的粘性标头.

I want to create navigation with anchor URL' and smooth scroll. But on that page I use a sticky header with a height of 88px.

如何基于类product-anchor-links-action创建平滑滚动?

How can I create a smooth scroll, based on class product-anchor-links-action?

JSFiddle: https://jsfiddle.net/rx0txmek/2/

JSFiddle: https://jsfiddle.net/rx0txmek/2/

我当前的HTML:

<div class="product-page-nav">
    <div class="container">
    <ol class="product-anchor-links-list">
        <li class="product-anchor-links-item"><a href="#productbeschrijving" class="product-anchor-links-action">Nav 1</a></li>
        <li class="product-anchor-links-item"><a href="#specificaties" class="product-anchor-links-action">Nav 2</a></li>
        <li class="product-anchor-links-item"><a href="#reviews" class="product-anchor-links-action">Nav 3</a></li>
    </ol>
    </div>
</div>

jQuery:

    $(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;
      }
    }
  });
});

推荐答案

只需从scrollTop值中减去粘性标头的高度.如果没有粘性,则该值为0(如果始终存在粘性,则可以使用.height()值.)

Just subtract the height of the sticky header from the scrollTop value. When there is no sticky, the value will be 0 (you can just use the .height() value if the sticky is always present).

$('a').click(function(){

    var stickyHeight = $('.sticky').length ? $('.sticky').height() : 0

    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top - stickyHeight 
    }, 500);
    return false;
});  

如果没有$('.stickyHeader')

If there is no $('.stickyHeader')

这篇关于平滑滚动锚点jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆