简体   繁体   English

如何滚动到模式的顶部

[英]How to scroll to the top of a modal

On my portfolio, I map over an array of projects that are rendered one after the next.在我的投资组合中,我在一系列项目上进行了 map,这些项目一个接一个地呈现。 Each project then has a button that opens a modal.然后每个项目都有一个打开模式的按钮。 The problem is if I open the modal on one project, scroll down, close the modal, and then open the modal on another project, this second modal will start at the same location the first one was closed.问题是如果我在一个项目上打开模态,向下滚动,关闭模态,然后在另一个项目上打开模态,第二个模态将从第一个模态关闭的相同位置开始。

It seems the issue has to do with where the modal is placed in the codebase, at the level where I initially map over the projects array and at the child level of a project.似乎问题与模态在代码库中的位置有关,在我最初 map 在项目数组和项目的子级别的级别。

window.scrollTo(0, 0) AND OR let getThisEle = document.getElementsByClassName('example') getThisEle.scrollTop = 0 do not work. window.scrollTo(0, 0) AND OR let getThisEle = document.getElementsByClassName('example') getThisEle.scrollTop = 0不起作用。

Many many hours went into creating this fix, I could not find a solution that worked online so I want to share it here to save future people my pain.创建此修复程序花费了很多时间,但我找不到在线工作的解决方案,因此我想在这里分享它以减轻未来的人们的痛苦。

You can change the button that opens your modal from a button/div element to be an <a></a> anchor element.您可以将打开模式的按钮从 button/div 元素更改为<a></a>锚元素。 Set the anchors href to be the top of the content in the modal.将锚点 href 设置为模式中内容的顶部。 Then go find your file that contains the top content of your modals and give it an id equal to the href.然后 go 找到包含模态框顶部内容的文件,并给它一个等于 href 的 id。

In my case, my button was an <a href="top-modal"> , and then I found the top heading for the content in my modal and gave it id="top-modal" .在我的例子中,我的按钮是一个<a href="top-modal"> ,然后我在我的模态中找到了内容的顶部标题,并给了它id="top-modal" This makes it so whenever you click the button that opens your modal, it will scroll to the top of that modal.这使得每当您单击打开模式的按钮时,它都会滚动到该模式的顶部。

Did you try scrollIntoView ?你试过scrollIntoView吗?

Here's some docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView这是一些文档: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM