如何在单击事件和使用普通JavaScript加载新页面后滚动到元素

如何在单击事件和使用普通JavaScript加载新页面后滚动到元素,javascript,html,css,Javascript,Html,Css,我将尝试以一种符合需求的方式来总结这一点,我希望这可以简化问题 单击锚定标记时,网页将用户导航到一个新页面,页面加载时,页面将滚动到与前面单击的锚定标记对应的元素 正如您将在代码中看到的,我试图利用CSS滚动行为属性。 到目前为止,我已经尝试了下面的代码,但是当我运行它时,我在开发人员控制台中收到一条错误消息,说明: TypeError:无法读取未定义的属性“offsetTop” 因此,我推测window.onload函数并不是在我想要加载的页面上启动的,而是在单击锚标记时所在的页面上启动的。

我将尝试以一种符合需求的方式来总结这一点,我希望这可以简化问题

单击锚定标记时,网页将用户导航到一个新页面,页面加载时,页面将滚动到与前面单击的锚定标记对应的元素

正如您将在代码中看到的,我试图利用CSS滚动行为属性。

到目前为止,我已经尝试了下面的代码,但是当我运行它时,我在开发人员控制台中收到一条错误消息,说明: TypeError:无法读取未定义的属性“offsetTop” 因此,我推测window.onload函数并不是在我想要加载的页面上启动的,而是在单击锚标记时所在的页面上启动的。我如何更改代码,使其在指定页面中有效

HTML of Page A (where the anchor tag is located):

   <a id="ship-it" href="services.html" class="services">
    <div id="image-container_4">
      <div id="image_4">
        <div id="overlay_4"></div>
        <h2 class="h2">We pack it and ship it</h2>
        <img id=imageB src="/images/shipping.jpg" alt="">
      </div>
    </div>
  </a>

HTML of Page B (where the target element is located):
<section id="manufacturing-section" class="section">

    <img src="/images/manufacturingMelting2.jpg" alt="Magnetic Particle Inspection">

    <div id="manufacturing-container">
      <h2> <span>Manufacturing</span> <br> We provide high quality, low cost solutions to meet your requirements.</h2>

      <p>
        soemthing something something, DarkSide...
      </p>

    </div>

  </section>

JS / CSS:

function scrollIt(element) {
  window.scrollTo({
    'behavior': 'smooth',
    'left': 0,
    'top': element.offsetTop
  });
}


const serviceAnchor = document.querySelectorAll('.services');
//'serviceAnchor' is located on page A
const sections = document.querySelectorAll('.section');
// 'sections' is located on page B and represents the element the page should scroll to when the page has loaded after the corresponding anchor tag was clicked


serviceAnchor[0].addEventListener('click', () =>  {
  window.onload = scrollIt(sections[0]);
});

serviceAnchor[1].addEventListener('click', () =>  {
  window.onload = scrollIt(sections[1]);
 });

 serviceAnchor[2].addEventListener('click', () =>  {
  window.onload = scrollIt(sections[2]);
 });

 serviceAnchor[3].addEventListener('click', () =>  {
  window.onload = scrollIt(sections[3]);
 });
页面A的HTML(锚定标记所在的位置): 页面B的HTML(目标元素所在的位置): 制造
我们提供高质量、低成本的解决方案,以满足您的要求。 有什么事,黑暗的一面。。。

JS/CSS: 函数scrollIt(元素){ window.scrollTo({ “行为”:“平滑”, “左”:0, “顶部”:element.offsetTop }); } constServiceAnchor=document.querySelectorAll('.services'); //“serviceAnchor”位于第A页 const sections=document.querySelectorAll('.section'); //“sections”位于页面B上,表示在单击相应的锚定标记后加载页面时页面应滚动到的元素 serviceAnchor[0]。addEventListener('单击',()=>{ window.onload=scrollIt(节[0]); }); serviceAnchor[1]。addEventListener('单击',()=>{ window.onload=scrollIt(第[1]节); }); serviceAnchor[2]。addEventListener('单击',()=>{ window.onload=scrollIt(第[2]节); }); serviceAnchor[3]。addEventListener('单击',()=>{ window.onload=scrollIt(第[3]节); });
出现错误的原因是无法跨页面加载运行javascript。假设您使用的是传统站点而不是单页应用程序,当浏览器加载新页面时,当前页面上的所有javascript都将停止


浏览器已经支持使用
www.site.com#myElementId
语法在页面加载时跳转到元素。如果您想要平滑滚动,您需要传递元素的id以在url中滚动,或者其他一些方式,比如在localstorage中缓存其id,然后在另一个页面的pageload上运行平滑滚动js。

您不能导航到其他页面,然后要求浏览器启动一段JavaScript。这将是一个巨大的安全问题,因为我可以让你点击到my-bank.com的链接,然后使用JavaScript访问你的秘密cookie或本地存储,并入侵你的帐户

您唯一能做的就是链接到链接页面内的锚,并将使用默认的滚动行为(对于大多数浏览器,没有平滑滚动,因为它的计算和资源密集度最低):

<!-- not possible -->
<a onclick="navigateThenDoSomething()">Some link</a>
<!-- possible -->
<a href="some-url#some-section">Some link</a>

由于带有选项的
.scrollTo
JS方法与
滚动行为
具有相同的,并且您对此没有问题,因此您可以删除JS代码并设置:

html, body, .or-other-scrolling-container {scroll-behavior:smooth}
并使用锚链

因此,页面A的HTML将是,例如:

<a id="ship-it" href="services.html#manufacturing" class="services">
  <div id="image-container_4">
    <div id="image_4">
      <div id="overlay_4"></div>
      <h2 class="h2">We pack it and ship it</h2>
      <img id=imageB src="/images/shipping.jpg" alt="">
    </div>
  </div>
</a>

用于启用滚动的占位符
制造业
我们提供高质量、低成本的解决方案,以满足您的需求。 有些东西,黑暗的一面


所以你想点击一篇文章,加载另一个页面,然后当该页面加载时,你想滚动到新页面上的另一篇文章?@nicholasHarder从技术上讲,这不是一篇文章。是的,这就是我的想法。
console.log(sections)
写了什么吗?如果章节位于尚未加载的B页,则无法从A页访问这些章节?您在同一脚本中引用了A页和B页的元素。我将尝试一下。然而,这是假设我们仍然在同一页上。对吗?@Dan,这是假设我们从A页转到B页。这个例子是为了展示平滑滚动如何与锚链接一起工作。
html, body, .or-other-scrolling-container {scroll-behavior:smooth}
<a id="ship-it" href="services.html#manufacturing" class="services">
  <div id="image-container_4">
    <div id="image_4">
      <div id="overlay_4"></div>
      <h2 class="h2">We pack it and ship it</h2>
      <img id=imageB src="/images/shipping.jpg" alt="">
    </div>
  </div>
</a>
<a name="manufacturing"></a>
<section id="manufacturing-section" class="section">
  <img src="/images/manufacturingMelting2.jpg" alt="Magnetic Particle Inspection">
  <div id="manufacturing-container">
    <h2>
      <span>Manufacturing</span><br>
      We provide high quality, low cost solutions to meet your requirements.
    </h2>
    <p>something something something, DarkSide...</p>
  </div>
</section>