问题描述
当我转到页面时,我有一个页面名称url.com/yourfirstpage/默认情况下隐藏所有div(显示:无)
如果我们将#sec1定位为url.com/yourfirstpage/#sec1它只显示sec1并隐藏其他人。
我想知道我们是否在没有像url.com/yourfirstpage/这样的锚ID的情况下去了网址,它需要显示所有的div。
I have a page name url.com/yourfirstpage/ when i go to the page all the div are hidden by default (display:none)if we target #sec1 as url.com/yourfirstpage/#sec1 it only displays sec1 and hide others.I was wondering if we go the url without having anchor id like url.com/yourfirstpage/ it needs to show all the divs.
#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>
推荐答案
如果您能够修改HTML结构,这是一个技巧。我们的想法是让元素可见,然后使用:target
隐藏它们。由于我们没有先前的兄弟选择器或父选择器,因此我在父元素中使用id来选择任何元素:
Here is a trick in case you are able to modify your HTML structure. The idea is to have the elements visible and then we hide them using :target
. Since we don't have previous sibling selector or parent selector, I used id within a parent element to be able to select any element:
#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代码如下:
It can work with any number of sections and we can improve the CSS code as follow:
#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>
这篇关于如果没有点击链接,则显示所有div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!