admin管理员组

文章数量:1429399

I have 4 modals on a page. If I open one scroll to the bottom, close it, and reopen it, it puts me where I scrolled to last in the modal. This happens with every modal so if I scroll to the bottom of the first modal, close it and then open up the 3rd modal it will put me to the bottom of the modal.

I am trying to create a javascript funciton which scrolls the modal to the top onclick of the element which opens up the modal.

Any ideas would be greatly appreciated as I seem to not be able to find any solutions anywhere.

Thanks.

I have 4 modals on a page. If I open one scroll to the bottom, close it, and reopen it, it puts me where I scrolled to last in the modal. This happens with every modal so if I scroll to the bottom of the first modal, close it and then open up the 3rd modal it will put me to the bottom of the modal.

I am trying to create a javascript funciton which scrolls the modal to the top onclick of the element which opens up the modal.

Any ideas would be greatly appreciated as I seem to not be able to find any solutions anywhere.

Thanks.

Share Improve this question asked May 24, 2020 at 18:47 thomas_i_sthomas_i_s 451 gold badge1 silver badge4 bronze badges 1
  • 2 Wele to Stack Overflow! Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the stack snippet. – SMAKSS Commented May 24, 2020 at 18:53
Add a ment  | 

2 Answers 2

Reset to default 2

Use the element's .scroll() function. document.getElementById("element-id").scroll(0,0);

I hope this example helps you. In this example, we start from the top to a div down there. Then we go back to another div at the top.

It's simple. Get the div id and then its position on the screen with offsetTop. This value is then passed to the top option in window.scroll.

var myDiv = document.getElementById("myDiv");
var myDiv2 = document.getElementById("myDiv2");

function scrollMe(){
  scrollToMyDiv(myDiv);
}
function scrollMe2(){
  scrollToMyDiv(myDiv);
}
function scrollToMyDiv(element) {
  window.scroll({
    top: element.offsetTop,
    left: 0,    
    behavior: 'smooth'
  });
}
<a href="#" onclick="scrollMe()">scroll now</a>

<div id="myDiv2">
    <p>div 2</p>
</div>
<div style="height:200vh;background-color:lime;"></div>

<div id="myDiv" style="background-color:red">
  <p><a onclick="scrollMe2()" href="#">scroll to div 2</a></p>
</div>

本文标签: javascriptHow to scroll to the top of a div using either scrollTop or scrollToStack Overflow