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//原文链接
- html
- js
- scrollIntoView 属性
- 注:scrollTo
本文来自博客园,作者:时光凉忆,转载请注明原文链接:https://www.cnblogs.com/naturl/p/10762309.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)