【问题标题】:Use HTML anchor link to display a hidden div and scroll to desired anchor location使用 HTML 锚链接显示隐藏的 div 并滚动到所需的锚位置
【发布时间】:2019-05-17 01:21:17
【问题描述】:

我正在尝试创建一个索引页面,并希望拥有指向隐藏 div 内的锚点的链接。

单击锚链接将触发锚所在的 div 变为可见并将页面滚动到锚位置。

我尝试了一些方法,但都失败了。任何帮助将不胜感激。

<div>
  <p>Link</p>
  <a href="#content1">Content 1</a><a href="#content2">Content 2</a><a href="#content3">Content 3</a><a href="#content4">Content 4</a>
</div>
<div class="inter">Some intermedary content with a large bottom margin to demonstrate scroll</div>
<div>
  <div class="hiddenContent">
    <div id="content1">I am content 1</div>
    <div id="content2">I am content 2</div>
    <div id="content3">I am content 3 
    <a id="content4" >Inner anchor within content 3 div. Link should scroll here but also show the other content within content 3.</a>
    </div>
  </div>

【问题讨论】:

  • 请包括一个工作或半工作的例子。描述代码行为对任何人都没有帮助。

标签: javascript jquery wordpress anchor


【解决方案1】:

这可以通过 CSS 轻松解决。您需要进行调整以满足您的需求,因为您没有向我们提供任何可使用的代码。

使用:target pesuo-class 选择器选择作为链接目标的项目

.hiddenContent>div, .hiddenContent > [name=content4] {
  display: none;
}

.hiddenContent>div:target {
  display: block;
}

.inter {
  margin-bottom: 100vh;
}
<div>
  <p>Link</p>
  <a href="#content1">Content 1</a><a href="#content2">Content 2</a><a href="#content3">Content 3</a><a href="#content4">Content 4</a>
</div>
<div class="inter">Some intermedary content with a large bottom margin to demonstrate scroll</div>
<div>
  <div class="hiddenContent">
    <div id="content1">I am content 1</div>
    <div id="content2">I am content 2</div>
    <div id="content3">I am content 3</div>
    <a name="content4" >
        <div>Some content in a named anchor</div>
    </a>
  </div>

【讨论】:

  • 感谢您的快速回复!这解决了 1 个问题,但我仍然试图弄清楚如何滚动到隐藏 div 中的一个锚点。是否可以链接到该锚点并显示内容 1 div 的内容? (
    我是内容 1
    锚标题
    我满足 2
    我满足 3
    )
  • 这仍然会滚动到隐藏的目标,我已经修改为演示。在链接中的目标元素上使用 ID 而不是命名锚点。自 90 年代以来,我还没有见过有名字的主播。但是,命名锚也可以工作,请参阅更新的编辑。
  • 抱歉,我是新手,不知道如何在 cmets 中添加 HTML。问题是我需要在隐藏的 div 中有多个锚点。单击其中一个锚点时,它应该滚动锚点,但也会显示 div 中的其他内容。见这里prntscr.com/npm691
  • 如何点击隐藏 div 中的内容。如果 div 是隐藏的,那么锚点/链接也是如此。请edit您的问题提供一个更好的例子来说明您正在尝试做什么。
  • 更新希望有助于澄清。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多