我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
要求jquery和动画锚标签与指定的名称而不是id,同时添加哈希到浏览器url。还修复了大多数jquery答案中#符号没有带转义反斜杠前缀的错误。返回按钮,不幸的是,不能正确地导航回以前的哈希链接…
$('a[href*=\\#]').click(function (event)
{
let hashValue = $(this).attr('href');
let name = hashValue.substring(1);
let target = $('[name="' + name + '"]');
$('html, body').animate({ scrollTop: target.offset().top }, 500);
event.preventDefault();
history.pushState(null, null, hashValue);
});
其他回答
这将使jQuery很容易识别目标哈希并知道何时何地停止。
$('a[href*="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
我对"/xxxxx#asdf"和"#asdf" href锚都这样做了
$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];
if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});
本机支持在哈希id滚动上平滑滚动。
html {
scroll-behavior: smooth;
}
大家可以看看:https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
以下是我为多个链接和锚点实现的解决方案,用于平滑滚动:
http://www.adriantomic.se/development/jquery-localscroll-tutorial/ 如果你在导航div中设置了导航链接,并声明了这样的结构:
<a href = "#destinationA">
和你相应的锚标签目的地如下:
<a id = "destinationA">
然后把这个加载到文档的头部:
<!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>
<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>
<script type = "text/javascript">
$(document).ready(function()
{
// Scroll the whole document
$('#menuBox').localScroll({
target:'#content'
});
});
</script>
感谢@Adriantomic
要求jquery和动画锚标签与指定的名称而不是id,同时添加哈希到浏览器url。还修复了大多数jquery答案中#符号没有带转义反斜杠前缀的错误。返回按钮,不幸的是,不能正确地导航回以前的哈希链接…
$('a[href*=\\#]').click(function (event)
{
let hashValue = $(this).attr('href');
let name = hashValue.substring(1);
let target = $('[name="' + name + '"]');
$('html, body').animate({ scrollTop: target.offset().top }, 500);
event.preventDefault();
history.pushState(null, null, hashValue);
});