我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
本机支持在哈希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
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
这对我来说是完美的
经过测试和验证的代码
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);
//add hash to the current scroll position
window.location.hash = this.hash;
}
});
不需要任何js只是使用滚动行为:平滑的html标签就是这样
html{
scroll-behavior: smooth;
}