我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
这对我来说是完美的
其他回答
本机支持在哈希id滚动上平滑滚动。
html {
scroll-behavior: smooth;
}
大家可以看看:https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
这对我来说是完美的
只有CSS
html {
scroll-behavior: smooth;
}
你只需要加上这个。现在你的内部链接滚动行为将是流畅的像一个流。
程序化:一些额外的和高级的东西
// Scroll to specific values
// window.scrollTo or window.scroll
window.scroll({
top: 1000,
left: 0,
behavior: 'smooth'
});
// Scroll certain amounts from current position
window.scrollBy({
top: 250, // could be negative value
left: 0,
behavior: 'smooth'
});
// Scroll to a certain element
document.getElementById('el').scrollIntoView({
behavior: 'smooth'
})
注意:所有最新的浏览器(Opera, Chrome, Firefox等)都支持此功能。
要详细了解,请阅读这篇文章
添加:
function () {
window.location.hash = href;
}
是否使垂直偏移量无效
top - 72
Firefox和IE浏览器,但Chrome浏览器没有。基本上,页面平滑地滚动到基于偏移量它应该停止的位置,但然后向下跳转到没有偏移量的页面所在的位置。
它确实将哈希添加到url的末尾,但按下back并不会让你回到顶部,它只是从url中删除哈希,并留下它所在的查看窗口。
这是我使用的完整js:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top - 120
}, 500, function () {
window.location.hash = href;
});
return false;
});
HTML
<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
或使用绝对完整的URL
<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
jQuery
$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});