javascript - 当用户单击按钮时,如何使我的页面向下滚动?

标签 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/

上一篇:html - 如何使 <div> 中的行列网格居中。 HTML

下一篇:html - 使图像拉伸(stretch)到容器的边缘

相关文章:

javascript - Umbraco-Images 不显示现有 HTML 标记

javascript - Google Apps 脚本上的动态 <div> 高度

html - 在 Wordpress 中显示标题标签的问题

javascript - <span> 段落中的重叠字符串

javascript - jQuery 函数是否仍可用于 AJAX 调用返回的 HTML 表?

javascript - 客户端上的 Socket.io 路径,如何将它匹配到我的 node.js 服务器目录树?

javascript - 在 Chrome 中重新启用 window.alert

javascript - 使用 JCrop 重新缩放大图像

html - 将图像添加到代码中

css - 为什么 Firefox 中的矩形需要宽度和高度属性?