我是 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/