<分区>
标签 javascript html css
<分区>
我在主页上添加了一个按钮。我希望,当用户单击此按钮时,页面向下滚动到该按钮所指的相应部分(在我的例子中是我主页的商店部分)。当用户单击按钮时,如何插入页面向下滚动的代码?
我的网站是 hintdrop.com
最佳答案
您正在寻找片段标识符。
添加 id
属性到您要滚动到的部分。
示例:<section id="shop"> ... </section>
然后,使用 anchor <a>
用 href
代替按钮属性。
示例:<a href="#shop">Shop</a>
简单的例子:
#shop {
margin-top: 300vh;
background-color: tomato;
height: 100vh;
position: relative;
}
#shop::after {
content: 'Shop Content';
position: absolute;
color: white;
font-size: 3em;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
<a href="#shop">Shop</a>
<section id="shop"></section>
如果需要平滑滚动, scrollIntoView
可以这样使用:
document.querySelector('#shopBtn').addEventListener('click', function() {
document.querySelector('#shop').scrollIntoView({
behavior: 'smooth'
});
});
#shop {
margin-top: 300vh;
background-color: tomato;
height: 100vh;
position: relative;
}
#shop::after {
content: 'Shop Content';
position: absolute;
color: white;
font-size: 3em;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
<button id="shopBtn">Shop</button>
<section id="shop"></section>
关于javascript - 当用户单击按钮时,如何使我的页面向下滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48015963/