You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从子页返回主页后滚动至对应锚点的实现问题

解决锚点无法自动滚动的问题

Hey there, let's fix that anchor scrolling issue you're facing! First, let's break down what's going wrong with your current code, then walk through the corrected solution step by step.

问题分析

Looking at your existing code, there are two key issues preventing the scroll from working:

  1. In your homepage's load event, you're reassigning window.location to the full URL, which triggers a page reload and breaks the native anchor behavior.
  2. The line (toHash).offset().top is trying to call the offset() method on a string (your URL), which is a syntax error—browsers can't execute this at all.

修正后的解决方案

1. 子页返回逻辑(确保Hash格式正确)

First, make sure you're appending a valid hash (starting with #) to the URL. If pageIndex is just a number (like 1), we'll add the # explicitly:

$('.myClose').click(function(event) {
  event.preventDefault();
  // Ensure the hash starts with # (adjust if your pageIndex already includes it)
  const targetHash = pageIndex.startsWith('#') ? pageIndex : `#${pageIndex}`;
  window.location.href = this.href + targetHash;
});

2. 主页滚动逻辑(修复Load事件代码)

Remove the redundant window.location reassignment, then properly extract the hash and scroll to the target element:

$(window).on('load', function() {
  // Grab the hash from the current URL (e.g., "#1" from http://page#1)
  const targetHash = window.location.hash;
  
  // Only proceed if the hash exists and the target element is on the page
  if (targetHash && $(targetHash).length) {
    // Get the top position of the target element
    const targetPosition = $(targetHash).offset().top;
    // Smooth scroll to the element
    $('html, body').animate({ scrollTop: targetPosition }, 500);
  }
});

额外小提示

  • Double-check that your homepage has elements with matching id attributes (like <a href="portfolio/1/" id="1"> or any other element with id="1")—the scroll can't find something that doesn't exist!
  • If you're using fixed headers, you might want to subtract the header's height from targetPosition to avoid the anchor being hidden under the header.

内容的提问来源于stack exchange,提问作者Tasos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:32:54