如何修改它以便我可以滚动到类而不是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>
答案 0 :(得分:1)
您可以使用fetched值获取类名,然后按类定位元素:
var target = this.hash;
var $target = $('.'+target.replace('#',''));
<强> Working Demo 强>
答案 1 :(得分:0)
尝试以下代码
// 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;