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
2 Answers
Reset to default 2Use 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
版权声明:本文标题:javascript - How to scroll to the top of a div using either scrollTop or scrollTo - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745544253a2662633.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论