jQuery ScrollTo锚链接但类不是ID

时间:2015-04-21 11:18:51

标签: javascript jquery html

如何修改它以便我可以滚动到类而不是ID?

JS:

// Scroll To # Links
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});

HTML:

<a href="#test">test link</a>

<div class="test" style="margin-top: 1000px;">
    testing content
</div>

JSFIDDLE

2 个答案:

答案 0 :(得分:1)

您可以使用fetched值获取类名,然后按类定位元素:

 var target = this.hash;
 var $target = $('.'+target.replace('#',''));

<强> Working Demo

答案 1 :(得分:0)

尝试以下代码

&#13;
&#13;
// Scroll To # Links
$('a[href^="#"]').on('click', function(e) {
  e.preventDefault();

  var target = this.hash;
  target = target.replace('#', '');
   var $target = $('.' + target);

  $('html, body').stop().animate({
    'scrollTop': $target.offset().top
  }, 700, 'swing', function() {
    window.location.hash = '#' + target;
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#test">test link</a>

<div class="test" style="margin-top: 1000px;">
  testing content
</div>
&#13;
&#13;
&#13;