javascript - 如何使页面自动滚动到内容中的元素?

标签 javascript jquery parallax

我是 javascript 和 jquery 的新手,所以我不确定从哪里开始。

我正在做一个项目,如果页面可以在用户不活动几秒钟后自动滚动到某个视口(viewport),那就太好了。

这可以在https://www.nfrealmusic.com/#store中看到当它自动滚动到加载时的特定部分并在您在“商品”和“音乐”部分之间向下滚动一点时完成滚动。

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  height: 250px;
  width: 250px;
  overflow: auto;
  background: green;
}

#content {
  margin:500px;
  height: 800px;
  width: 2000px;
  background-color: coral;
}
</style>
</head>
<body>

<p>Click the button to scroll to the top of the element with id="content".</p>

<button onclick="myFunction()">Scroll</button>

<div id="myDIV">
  <div id="content">
  Some text inside an element.
  </div>
</div>

<script>
function myFunction() {
  var elmnt = document.getElementById("content");
  elmnt.scrollIntoView();
}
</script>

https://codepen.io/Fullstack_developer/pen/bGGKNJX

希望它无需按下按钮即可自动滚动到 View 中!

这可以用 jquery 或 velocityjs 完成吗?

感谢您的帮助!

最佳答案

function myFunction() {
  var elmnt = document.getElementById("content");
  elmnt.scrollIntoView();
}
#myDIV {
  height: 250px;
  width: 250px;
  overflow: auto;
  background: green;
}

#content {
  margin: 500px;
  height: 800px;
  width: 2000px;
  background-color: coral;
}
<body onload="myFunction()">

  <p>Click the button to scroll to the top of the element with id="content".</p>

  <button onclick="myFunction()">Scroll</button>

  <div id="myDIV">
    <div id="content">
      Some text inside an element.
    </div>
  </div>
</body>

关于javascript - 如何使页面自动滚动到内容中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761792/

相关文章:

javascript - JavaScript 的数组过滤方法在 IE 7 中不起作用

javascript - 如何修改 Material-UI <Select> 下拉 div 的 z-index?

javascript在循环中传递变量

jQuery 滑动动画不起作用

javascript - jQuery 视差导航不会滚动到目标

android - 使用官方支持库 23.x.+bottomSheet 像谷歌地图一样向上滑动图像

javascript - 使用 jQuery 暂时延迟页面滚动

javascript - WordPress admin-ajax.php 总是返回 0

javascript - Jquery认为表是空的

javascript - imageScroll.js 视差背景图像