css 在Safari中,指向同一页面上div的锚链接不起作用

ecbunoof  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(130)

我有一个基于React的网站,包括每个页面顶部的链接列表:

<ul>
    <li><a href="/">HOME</a></li>
    <li><a href="/about-us">ABOUT US</a></li>
    <li><a href="/#contactSection">CONTACT US</a></li>
</ul>

在主页的底部,我有这样一段HTML:

<section id="contactSection" className="contactSection ptb_100">
    <h2>Contact Us</h2>
    ...HTML FORM...
</section>

当我点击主页顶部的“联系我们”链接时,Chrome会滚动到contactSection标识的正确HTML,而Safari会滚动到页面顶部。当我点击网站上另一个页面的“联系我们”链接时,或者如果我在地址栏中输入#contactSection并按Enter键,Safari会正确滚动。
我看过一些建议在href中添加/的帖子,但似乎没有效果。有什么建议吗?

UPDATE问题的原因是页面顶部的粘滞标头导致Safari将页面保持在顶部。移除粘滞标头解决了问题,但不确定原因。

kx7yvsdv

kx7yvsdv1#

您不应该为相同的页面ID链接添加“/”

第一个

nzk0hqpo

nzk0hqpo2#

试试这个(根据下面的评论编辑)
在HTML中:

<li>
  <a href="#contactSection" onclick="scrollToElement('#contactSection')">CONTACT US</a>
</li>

在JS中:

// kicks in if href doesn't work
function scrollToElement(id) {
  const el = document.querySelector(id);
  if (el) {
    el.scrollIntoView();
  }
}

// when redirected to the page from somewhere else
window.addEventListener('DOMContentLoaded', (event) => {
  const { href } = window.location;
  if (href.lastIndexOf('#')) {
    const id = href.substring(href.lastIndexOf('#'), href.length);
    scrollToElement(id);
  }
});

相关问题