简体   繁体   English

居中通过#滚动到Element to。 (无需修改DOM /使用引用)

[英]Centering Scroll to Element to via # ? (without modifying the DOM / using refs)

I would like to scroll to a certain element via # : 我想通过#滚动到某个元素:

<a href="#element">Element</a>

<div name="element" />

It accomplishes this quite well, but it goes to the very top of the element. 它可以很好地完成此任务,但是它到达了元素的最上层。 However, I'd like the element scrolled to to be centered for the user. 但是,我希望元素滚动到用户的中心。

I am hesitant to use Javascript's scrollTo or other, external libraries, since I will need to use this functionality a lot (very, very much). 我不愿意使用Javascript的scrollTo或其他外部库,因为我将需要大量使用此功能(非常非常)。 I am using React and don't want to overuse refs and slow down my app. 我正在使用React,并且不想过度使用refs和降低我的应用速度。 So I'd like to accomplish this with HTML only, preferably. 因此,我希望仅使用HTML来完成此操作。 JS is fine too, of course, but most solutions I came across modify the DOM and/or use refs . JS当然也可以,但是我遇到的大多数解决方案都是修改DOM和/或使用refs

There is probably a better/cleaner way to do it, but with only html/css, the only thing that I think about is to use a hidden span under your div element, like so: 可能有更好/更干净的方法,但是只有html / css,我唯一想到的就是在div元素下使用隐藏的span,如下所示:

 html { scroll-behavior: smooth; } .space { width: 100%; height: 400px; background-color: blue; } #element { position: relative; top: -50vh; visibility: hidden; } 
 <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <a href="#element">Element</a> <div class="space"></div> <p> some text </p> <div class="space"></div> <p> some text </p> <div class="space"></div> <div> <p> Your element </p> <span id="element">anchor </span> </div> <div class="space"></div> </body> </html> 

AFAIK, no way to achieve your desirable effect without a bit of js. AFAIK,没有一点js就无法达到理想的效果。 As for "centered", then some calculation is needed. 至于“居中”,则需要一些计算。

 <html> <head> <title>Document</title> <style> .placeholder { height: 1000px; } </style> <script> function scrollToDest(event) { var id = event.target.getAttribute("href"); if (id.charAt(0) !== "#") return; // not a valid <a> element var dest = document.getElementById(id.substr(1)); if (!dest) return; // no destination found; event.preventDefault(); // calculate the top and bottom margin remained when dest is centered var margin = window.innerHeight - dest.clientHeight; // what if the dest's height is larger than viewport? if (margin < 0) margin = 0; window.scroll({ left: 0, top: dest.offsetTop - margin / 2, behavior: "smooth" }); } </script> </head> <body> <div class="placeholder"> <a href="#dest" onclick="scrollToDest(event)">Let's go!</a> </div> <div id="dest">ARRIVAL</div> <div class="placeholder"></div> </body> </html> 

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

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