[英]Smooth scroll to specific div after fixed header
Header 高度为 100 像素,position static。 意味着当我们向下滚动时,header 固定在顶部 position。 现在我需要的是,如果您单击按钮(单击我,)。 它应该平滑滚动到 div 'second'。 但由于 100px 固定 header 当前 jquery 代码无法正常工作(div 'second' 在标题后面)
<header class="header"></header>
<div class="first"><button type="button">Click Me!</button></div>
<div class="second">Hi</div>
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow'); });
position fixed
更改为position: sticky;
scroll-behavior: smooth;
--> html
scroll-margin-top
- https://caniuse.com/?search=scroll-margin-top支持 > 94%例子
* { box-sizing: border-box; } html { scroll-behavior: smooth; } body { margin: 0; }.header { position: sticky; top: 0; left: 0; min-height: 100px; background-color: #00f; padding: 1.5rem; }.first,.second { min-height: 600px; padding: 1.5rem; }.second { background-color: #000; color: #fff; scroll-margin-top: 100px; }
<header class="header"></header> <div class="first"> <a href="#second">Click Me </a> </div> <div class="second" id="second">Hi</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.