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

HTML中使用href实现页面无刷新滚动到指定区块功能失效求助

问题排查与修复方案

核心错误点

  • id属性定义不规范:你给<section>标签设置的id值前缀多带了#符号,HTML的id属性本身不需要加#,#仅作为锚点跳转时的id标识前缀使用。你当前设置id为#section1的话,只有跳转地址写成##section1才能匹配到对应元素,自然无法正常触发滚动。
  • 无效属性误用:href是<a>标签的专属属性,给<div>标签添加href不会被浏览器识别,无法触发跳转逻辑。
  • 跳转逻辑冗余:锚点跳转本身就是浏览器原生支持的无重载能力,不需要额外通过onclick修改window.location实现,直接用<a>标签即可。

修复后代码

<html lang="en">
<head>
    <title>Portfolio</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <style>
        /* 开启全局平滑滚动,无需JS即可实现滚动过渡效果 */
        html {
            scroll-behavior: smooth;
        }
        /* 示例样式,给区块设置高度方便看到滚动效果,可按需替换为你自己的样式 */
        section {
            height: 100vh;
            width: 100%;
        }
    </style>
</head>
<body>
    <!-- id去掉前缀的# -->
    <section class="section1" id="section1"></section>
    <section class="section2" id="section2"></section>
    <section class="section3" id="section3"></section>
    <section class="section4" id="section4"></section>

    <footer>
        <div class="menu-btn">
            <div class="trep"></div>
            <!-- 把跳转元素从div替换为a标签,保留原有类名 -->
            <a href="#section2" class="chi-sono"></a>
            <a href="#section3" class="progetti"></a>
            <a href="#section4" class="contattami"></a>
        </div>
    </footer>
</body>
</html>

可选兼容方案

如果业务要求必须保留<div>标签不能替换为<a>标签,可以保留onclick逻辑,只需要修正id的定义即可正常触发滚动,不过更推荐使用<a>标签的语义化写法,可同时支持键盘聚焦、无障碍识别等能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:18:02