Как сделать так, чтобы страница автоматически прокручивалась до элемента внутри контента? - PullRequest
1 голос
/ 08 ноября 2019

Я новичок в javascript и jquery, поэтому я не уверен, с чего начать.

Я работаю над проектом, и было бы неплохо, если бы страница могла автоматически прокручиваться в определенный видовой экран после того, как пользователь неактивен в течение нескольких секунд.

Это можно увидеть в https://www.nfrealmusic.com/#store, когда он автоматически прокручивается до определенного раздела при загрузке и завершает прокрутку, когда вы прокручиваете немного больше между разделами «merch» и «music»,

<!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

хотели бы, чтобы он автоматически прокручивался в поле зрения без нажатия кнопки!

canэто можно сделать с помощью jquery или speedjs?

Спасибо за вашу помощь!

Ответы [ 2 ]

1 голос
/ 08 ноября 2019

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>
0 голосов
/ 08 ноября 2019

Вы вызываете прокрутку автоматически следующим образом:

window.onload = function(e){
  var elmnt = document.getElementById("content");
  elmnt.scrollIntoView();
}

С помощью jQuery вы можете использовать .animate () для прокрутки без нажатия кнопки, как показано ниже:

$(document).ready(function(){
$("#content").animate({ scrollTop: "300px" });
});

window.onload = function(e){
  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;}
<!doctype html>
<body>

<p>After loading, it will automatically scroll to the top of the element with id="content".</p>


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