我在主页上添加了一个按钮。我希望,当用户点击此按钮时,页面向下滚动到按钮所指的相应部分(在我的情况下,我的主页的商店部分)。当用户点击按钮时,如何为页面插入代码向下滚动?
我的网站是hintdrop.com
答案 0 :(得分:1)
您正在寻找片段标识符。
将id
属性添加到要滚动到的部分。
示例:<section id="shop"> ... </section>
然后,使用锚点<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;
}
&#13;
<a href="#shop">Shop</a>
<section id="shop"></section>
&#13;
如果需要平滑滚动,scrollIntoView
可以像这样使用:
document.querySelector('#shopBtn').addEventListener('click', function() {
document.querySelector('#shop').scrollIntoView({
behavior: 'smooth'
});
});
&#13;
#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;
}
&#13;
<button id="shopBtn">Shop</button>
<section id="shop"></section>
&#13;
答案 1 :(得分:0)
你也可以尝试使用ahref并给它一个id,这样当点击它时,它会移动到一个特定的部分。
答案 2 :(得分:0)
最简单的答案:在您的div或其他标签中创建 id ,然后在您的主播或href标签中,将您的ID名称链接到那里。
示例:
printf