简体   繁体   English

使页面滚动以将 div 放在顶部

[英]make the page scroll to put div on top

I'm building a page where I have some divs with different heights and a text inside them, I'd like to, when I click on div's text, to make the page move so that this div would get at the top of the screen.我正在构建一个页面,其中有一些具有不同高度的 div 和其中的文本,我想在单击 div 的文本时移动页面,以便该 div 位于屏幕顶部.

I've searched around but what I find is often related to the fixed property, the thing is that I don't want to change the position property of the div, I'd like just the page to scroll automatically so that the div would be on top.我四处搜索,但我发现的通常与固定属性有关,问题是我不想更改 div 的 position 属性,我只想让页面自动滚动,这样 div 就会在上面。

Do you have any advice on where I could start?你对我可以从哪里开始有什么建议吗?

Thank you谢谢

 .container { width: 100vw; height: auto; }.element { padding: 50px; } #element-1 { background-color: beige; height: 500px; } #element-2 { background-color: darkSeaGreen; height: 200px; } #element-3 { background-color: coral; color: white; height: 800px; } #element-4 { background-color: MidnightBlue; color: white; height: 300px; }
 <div class="container"> <div class="element" id="element-1"> <h1>Some text</h1> </div> <div class="element" id="element-2"> <h1>Some text</h1> </div> <div class="element" id="element-3"> <h1>Some text</h1> </div> <div class="element" id="element-4"> <h1>Some text</h1> </div> </div>

If I correctly understand you, this will help you.如果我正确理解你,这将帮助你。

 let divs = document.querySelectorAll(".element"); divs.forEach(div => { div.addEventListener("click", event =>{ let divTop = div.offsetTop; window.scrollTo(0, divTop); console.log(divTop + " --- " + window.scrollY); }); });
 .container { width: 100vw; height: auto; }.element { padding: 50px; } #element-1 { background-color: beige; height: 500px; } #element-2 { background-color: darkSeaGreen; height: 200px; } #element-3 { background-color: coral; color: white; height: 800px; } #element-4 { background-color: MidnightBlue; color: white; height: 300px; }
 <div class="container"> <div class="element" id="element-1"> <h1>Some text</h1> </div> <div class="element" id="element-2"> <h1>Some text</h1> </div> <div class="element" id="element-3"> <h1>Some text</h1> </div> <div class="element" id="element-4"> <h1>Some text</h1> </div> </div>

You would need to implement a function that does this您需要实现一个 function 来执行此操作

window.scrollTo(x, 0); 

where x is the position of the element.其中 x 是元素的 position。 You can get that by using你可以通过使用

let x = element.getBoundingClientRect().top;

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

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