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

如何通过其他页面的链接指定目标页面仅显示对应内容项?

跨页面链接指定显示对应内容项的实现方案

要实现点击页面1的链接后跳转至页面2,并仅显示对应分类的内容项,仅靠锚点链接无法完成隐藏其他内容的操作,需要结合JavaScript处理URL中的锚点信息,控制内容区块的显示与隐藏。

步骤1:优化页面2的HTML结构

给所有内容区块添加一个通用类(比如content-section),方便批量操作:

<div>
     <div class="content-section" id="webdesign-filter">
      <h4>Web Design</h4>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>

    <div class="content-section" id="responsive-filter">
      <h4>Responsive</h4>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>

    <div class="content-section" id="wordpress-filter">
      <h4>Wordpress</h4>
      <p>Lorem ipsum dolor sit amet.</p>
    </div>
</div>

步骤2:添加基础样式(可选)

定义一个hidden类用于隐藏元素,相比直接操作style更符合语义化,还能扩展过渡效果:

.content-section {
    /* 默认显示所有区块 */
    display: block;
}
.hidden {
    display: none;
}

步骤3:编写页面2的JavaScript逻辑

在页面2中添加以下脚本,读取URL锚点并控制内容显示:

document.addEventListener('DOMContentLoaded', function() {
    // 获取URL中的锚点(去除开头的#)
    const targetId = window.location.hash.slice(1);
    const allSections = document.querySelectorAll('.content-section');

    if (targetId) {
        // 隐藏所有内容区块
        allSections.forEach(section => {
            section.classList.add('hidden');
        });
        // 显示对应锚点的区块
        const targetSection = document.getElementById(targetId);
        if (targetSection) {
            targetSection.classList.remove('hidden');
            // 可选:平滑滚动到目标区块位置
            targetSection.scrollIntoView({ behavior: 'smooth' });
        }
    } else {
        // 无锚点时显示所有内容
        allSections.forEach(section => {
            section.classList.remove('hidden');
        });
    }
});

页面1的链接无需修改

保持原有的锚点链接格式即可:

<ul class="portfolio-filters list-inline">
    <li ><a href="page2.html/#webdesign-filter">Web Design</a></li>
    <li ><a href="page2.html/#responsive-filter">Responsive</a></li>
    <li ><a href="page2.html/#wordpress-filter">Wordpress</a></li>
 </ul>

内容的提问来源于stack exchange,提问作者Mohamed Amine belgareg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:05:32