如果未单击任何链接,则显示所有div

时间:2019-01-09 00:02:03

标签: javascript html css

我有一个页面名称url.com/yourfirstpage/,当我转到该页面时,默认情况下所有div都隐藏(显示:无) 如果我们将#sec1定位为url.com/yourfirstpage/#sec1,则仅显示sec1并隐藏其他内容。 我想知道我们是否要在没有url.com/yourfirstpage/之类的锚ID的情况下进入url,它需要显示所有div。

#sec1, #sec2, #sec3{
	display:none;
}
#sec1:target{
	display:block;
}
#sec2:target{
	display:block;
}
#sec3:target{
	display:block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</div>

2 个答案:

答案 0 :(得分:2)

如果您能够修改HTML结构,这是一个技巧。想法是使元素可见,然后我们使用:target隐藏它们。由于我们之前没有兄弟选择器或父选择器,因此我在父元素中使用了id来选择任何元素:

#sec1:target .page:nth-child(n+2){
  display: none;
}

#sec2:target .page:nth-child(2n+1){
  display: none;
}

#sec3:target .page:nth-last-child(n+2){
  display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1">
  <div id="sec2">
    <div id="sec3">
      <div class="page"> this is sec1</div>
      <div class="page"> this is sec2</div>
      <div class="page"> this is sec3</div>
    </div>
  </div>
</div>

它可以处理任意数量的部分,我们可以如下改进CSS代码:

#sec1:target .page:not(:nth-child(1)),
#sec2:target .page:not(:nth-child(2)),
#sec3:target .page:not(:nth-child(3)),
#sec4:target .page:not(:nth-child(4)),
#sec5:target .page:not(:nth-child(5)) {
  display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<a href="#sec4">sec4</a>
<a href="#sec5">sec5</a>

<div id="sec1">
  <div id="sec2">
    <div id="sec3">
      <div id="sec4">
        <div id="sec5">
          <div class="page"> this is sec1</div>
          <div class="page"> this is sec2</div>
          <div class="page"> this is sec3</div>
          <div class="page"> this is sec4</div>
          <div class="page"> this is sec5</div>
        </div>
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:1)

这种快速方法可能会有所帮助

您可以使用postcss插件在CSS中使用!选择器

[...document.querySelectorAll('a')].forEach(a => {
    a.addEventListener('click', () => {
        a.parentElement.classList.add('targeted')
    })
})
.targeted div {
  display: none;
}
.targeted div:target {
  display: block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</div>