我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
这将使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;
}
}
});
现在的浏览器要快一些。setInterval可能有用。现在这个功能在Chrome和Firefox中运行良好。(safari有点慢,不用IE)
function smoothScroll(event) {
if (event.target.hash !== '') { //Check if tag is an anchor
event.preventDefault()
const hash = event.target.hash.replace("#", "")
const link = document.getElementsByName(hash)
//Find the where you want to scroll
const position = link[0].getBoundingClientRect().y
let top = 0
let smooth = setInterval(() => {
let leftover = position - top
if (top === position) {
clearInterval(smooth)
}
else if(position > top && leftover < 10) {
top += leftover
window.scrollTo(0, top)
}
else if(position > (top - 10)) {
top += 10
window.scrollTo(0, top)
}
}, 6)//6 milliseconds is the faster chrome runs setInterval
}
}
CSS3的新热点。这比本页列出的所有方法都要简单得多,而且不需要Javascript。只需输入下面的代码到你的css和所有的链接指向你自己的页面内的位置将有一个平滑的滚动动画。
html{scroll-behavior:smooth}
之后,任何指向div的链接都将平滑地滑到这些部分。
<a href="#section">Section1</a>
编辑:对于那些对上面的一个标签感到困惑的人。基本上它是一个可点击的链接。然后你可以在你的网页的某个地方有另一个div标签
<div id="section">content</div>
在这种情况下,a链接将是可点击的,并将转到#section是什么,在这种情况下,它是我们称为section的div。
顺便说一句,我花了好几个小时才让它工作。在一些晦涩的评论区找到了解决方案。它是错误的,不会工作在一些标签。对身体不起作用。当我把它放在CSS文件中的html{}中时,它终于工作了。
此解决方案也适用于以下url,而不会破坏指向不同页面的锚点链接。
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
我还没有在所有浏览器中测试这个功能。
如果你在页面上有一个简单的按钮可以向下滚动到一个div,并且希望返回按钮通过跳到顶部来工作,只需添加以下代码:
$(window).on('hashchange', function(event) {
if (event.target.location.hash=="") {
window.scrollTo(0,0);
}
});
这也可以扩展到跳转到不同的div,通过读取哈希值,并像Joseph Silbers的答案一样滚动。