如何向下滚动并在同一页面上显示部分?



我正在开发一个单页网站,当用户点击一个特定的按钮时,它应该向下滚动到页面的另一个部分。

谁能指导我怎么做?

我认为CSS属性scroll-padding-top是你的答案。

您有不同的选项来解决这个

第一种方法是只使用HTML滚动到具有特定id

的元素

html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<a href="#readmore">Scroll down</a>
<h1 id="readmore">
Read More
</h1>

第二种方法是使用scrollIntoView方法,将指定的元素滚动到浏览器窗口的可见区域。

const element = document.getElementById("readmore");
document.getElementById('btn').addEventListener('click', () => {
element.scrollIntoView();
})
html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<button id="btn">Scroll down</button>
<h1 id="readmore">
Read More
</h1>

第三种方法是硬编码我想滚动的特定位置,在这种情况下,我将其设置为2000px(高度)

const element = document.getElementById("readmore");
document.getElementById('btn').addEventListener('click', () => {
window.scrollTo(0, 2000);
})
html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<button id="btn">Scroll down</button>
<h1 id="readmore">
Read More
</h1>

最新更新