a标签锚点平滑跳转 && 使用scrollIntoView && 注:2022-09-06更新
使用 scrollIntoView 实现锚点平滑跳转
html
<button class="btn">跳转</button>
<!-- ... -->
<div class="container">锚点区域</div>
js
document.querySelector('.btn').onclick = function (){
document.querySelector('.container').scrollIntoView({
behavior: "smooth",
block: "center",
inline: "nearest"
})
}
scrollIntoView 属性
behavior
定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"block
定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"inline
定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"
注:scrollTo
如果想滚动到屏幕指定位置可以使用 scrollTo(xpos, ypos)
window.scrollTo(0, 100px)
2022-09-06之前代码
一、创建锚点
<div class="header" id="top">//终点标签,添加一个id <a href="#top" class="fixed_top_a">^</a>//a标签href添加#id
锚点跳转很生硬,很不友好,找了两种平滑的跳转方法
二、平滑跳转
$('a[href*=#],area[href*=#]').click(function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body').animate({ scrollTop: targetOffset }, 1000); return false; } } }); https://blog.csdn.net/u012011360/article/details/78972858//原文链接
$(".fixed_btn").click(function () { $("html, body").animate({scrollTop: $($(this).attr("href")).offset().top -20+ "px"}, 500); return false; }); https://blog.csdn.net/never_tears/article/details/53377123//原文链接
本文来自博客园,作者:时光凉忆,转载请注明原文链接:https://www.cnblogs.com/naturl/p/10762309.html