这个问题在这里已有答案:
我在主页上添加了一个按钮。我希望,当用户点击此按钮时,页面向下滚动到按钮所指的相应部分(在我的情况下,我的主页的商店部分)。当用户点击按钮时,如何为页面插入代码向下滚动?
我的网站是hintdrop.com
您正在寻找片段标识符。
将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;
}
<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>
你也可以尝试使用一个href并给它一个id,所以当它点击时,它将移动到一个特定的部分。
最简单的答案:在你的div或其他标签中创建一个id,然后在你的锚或href标签中,在那里链接你的id的名字。
例:
<!--remember that ID links inside your html tag, should always have a hashtag (#)-->
<a href="#thisismydiv">JUMP TO MY DIVISION</a>
<!--your codes--->
<div id="thisismydiv">I am div!</div>