【问题标题】:Smooth scroll anchor jquery平滑滚动锚jquery
【发布时间】:2017-03-20 20:00:16
【问题描述】:

我想用锚 URL 和平滑滚动创建导航。 但在那个页面上,我使用了一个高度为 88px 的粘性标题。

如何根据 product-anchor-links-action 类创建平滑滚动?

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

【问题讨论】:

  • 您知道您没有任何 id 为 reviews 的元素,对吗?!....我真的不明白您的问题,因为您在 jsFiddle 中拥有所需的一切,看起来像你没有花太多精力去理解你的代码
  • @A.Wolff 感谢您的回复。是的,我知道,但我改变了小提琴,所以这是完整的。唯一的问题是我无法正确/工作。平滑滚动不起作用,无法正确滚动,它基于类。
  • 您的 jsFiddle 按预期工作,所以也许可以解释一下您的期望是什么? that it is based on the class什么意思?
  • @A.Wolff 谢谢!它目前可以工作,但它确实检查a href,而不是类名product-anchor-links-action。所以 to 应该只适用于具有该类的元素。这样其他 类就不会受到影响。
  • $('.product-anchor-links-action').click(...);?!

标签: jquery html css


【解决方案1】:

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

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

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

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

如果没有$('.stickyHeader')

【讨论】:

猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 2013-08-14
  • 2013-11-16
  • 1970-01-01
  • 2012-05-20
相关资源
最近更新 更多