繁体   English   中英

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

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

我想通过#滚动到某个元素:

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

<div name="element" />

它可以很好地完成此任务,但是它到达了元素的最上层。 但是,我希望元素滚动到用户的中心。

我不愿意使用Javascript的scrollTo或其他外部库,因为我将需要大量使用此功能(非常非常)。 我正在使用React,并且不想过度使用refs和降低我的应用速度。 因此,我希望仅使用HTML来完成此操作。 JS当然也可以,但是我遇到的大多数解决方案都是修改DOM和/或使用refs

可能有更好/更干净的方法,但是只有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,没有一点js就无法达到理想的效果。 至于“居中”,则需要一些计算。

 <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