我的页面上有几个超链接。用户在访问我的帮助部分时将阅读的常见问题解答。
使用锚点链接,我可以使页面滚动到锚点并将用户引导到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义 JavaScript 库。也许jQuery提供了这样的东西?
2018年<>月更新:现在有一种本机方法可以做到这一点:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
目前仅在最前沿的浏览器中支持此功能。
对于较旧的浏览器支持,您可以使用以下jQuery技术:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
这是小提琴:http://jsfiddle.net/9SDLw/
如果您的目标元素没有 ID,并且您通过其 链接到它,请使用以下命令:name
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
为了提高性能,您应该缓存该选择器,以便它不会在每次单击锚点时运行:$('html, body')
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
如果要更新 URL,请在回调中执行此操作:animate
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
CSS3 中的新热点。这比本页上列出的每种方法都要容易得多,并且不需要Javascript。只需在css中输入以下代码,突然指向您自己页面内位置的链接将具有流畅的滚动动画。
html{scroll-behavior:smooth}
之后,指向 div 的任何链接都将平滑地滑到这些部分。
<a href="#section">Section1</a>
编辑:对于那些对上述标签感到困惑的人。基本上它是一个可点击的链接。然后,您可以在网页中的某个位置添加另一个 div 标签,例如
<div id="section">content</div>
在这方面,链接将是可点击的,并将转到任何#section,在这种情况下,这是我们称为部分的div。
顺便说一句,我花了几个小时试图让它工作。在一些晦涩的评论部分找到了解决方案。它是有缺陷的,在某些标签中不起作用。在身体里不起作用。当我把它放在 CSS 文件中的 html{} 中时,它终于起作用了。
正确的语法是:
//Smooth scrolling with links
$('a[href^=\#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().top}, 500);
});
简化:干
function smoothScrollingTo(target){
$('html,body').animate({scrollTop:$(target).offset().top}, 500);
}
$('a[href^=\#]').on('click', function(event){
event.preventDefault();
smoothScrollingTo(this.hash);
});
$(document).ready(function(){
smoothScrollingTo(location.hash);
});
解释 :href^=\#
^
表示它与包含字符的内容匹配。因此,仅匹配锚点以确保它是同一页面的链接(感谢Peter Wong的建议)。#
\
是因为 是 CSS 选择器中的一个特殊字符,所以我们必须转义它。#
模板简介:该模板名称为【JavaScript 单击锚链接时平滑滚动】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。