如何通过单击超链接:target
1 个红色小框transition
为黄色圆圈,然后使同一个小框过渡为蓝色正方形?
这是我为红色小方 block 设计的 CSS:
#Redsquare{
height: 15px;
width: 15px;
background-color: rgb(255,0,0);
position: absolute;
top: 330px;
left: 640px;
transition: all 0.5s linear;
}
这是将 #Redsquare
定位到黄色圆圈的代码。
#Redsquare:target{
height: 300px;
width: 300px;
border-radius: 50%;
background-color: rgb(255,255,0);
top: 200px;
left: 500px;
}
但我希望通过按下另一个按钮,同样的小圆圈也能变成蓝色方 block 。
最佳答案
这是可以做到的。但它需要嵌套在 HTML 中,如下面的代码所示。如果您需要将相同的 div
转换超过两到三次,请不要使用此方法,因为标记会变得太杂乱。
基本上我们在这里做的事情如下:
- 将要转换的元素是类为
box
的div
。但它如何以及将被转换成什么取决于被点击的链接和相关联的目标。 - 当第一个链接被点击时,最外层带有
黄色圆圈
的div
是目标。根据 CSS,当target
为Yellowcircle
时,具有类box
的元素将转换为黄色圆圈。 - 当点击第二个链接时,
Bluesquare
div 成为target
并且在这种情况下根据 CSS,box
应该成为蓝色方 block 。 - 最后,当点击第三个链接时,目标是一般的
#
,所以默认的.box
CSS 样式将被应用,它会变回红色正方形。
还有其他替代方案,但它们涉及 JavaScript。
.box {
height: 150px;
width: 150px;
background-color: rgb(255, 0, 0);
transition: all 0.5s linear;
}
#Yellowcircle:target .box {
border-radius: 50%;
background-color: rgb(255, 255, 0);
}
#Bluesquare:target .box {
background-color: rgb(0, 0, 255);
}
/* Just for demo */
a {
position: relative;
margin: 0px 4px;
text-decoration: none;
font-family: Calibri;
font-variant: small-caps;
color: crimson;
}
a:after {
position: absolute;
content: "|";
padding: 0px 4px;
}
a:last-of-type:after {
display: none;
}
<div id='Yellowcircle'>
<div id='Bluesquare'>
<div class='box'>
</div>
</div>
</div>
<a href='#Yellowcircle'>Transform to yellow circle</a>
<a href='#Bluesquare'>Transform to blue square</a>
<a href='#'>Go back to default</a>
这就是我所说的标记在需要转换为 3 种以上的形状时变得凌乱的意思。请注意,我们必须如何为所需的每个额外形状引入额外级别。
.box {
height: 150px;
width: 150px;
background-color: rgb(255, 0, 0);
transition: all 0.5s linear;
}
#Yellowcircle:target .box {
border-radius: 50%;
background-color: rgb(255, 255, 0);
}
#Bluesquare:target .box {
background-color: rgb(0, 0, 255);
}
#Greenoval:target .box {
border-radius: 75px 100px;
background-color: rgb(0, 255, 0);
}
/* Just for demo */
a {
position: relative;
margin: 0px 4px;
text-decoration: none;
font-family: Calibri;
font-variant: small-caps;
color: crimson;
}
a:after {
position: absolute;
content: "|";
padding: 0px 4px;
}
a:last-of-type:after {
display: none;
}
<div id='Yellowcircle'>
<div id='Bluesquare'>
<div id='Greenoval'> <!-- notice how for each shape we need to add an extra level -->
<div class='box'>
</div>
</div>
</div>
</div>
<a href='#Yellowcircle'>Transform to yellow circle</a>
<a href='#Bluesquare'>Transform to blue square</a>
<a href='#Greenoval'>Transform to green oval</a>
<a href='#'>Go back to default</a>
关于html - :target 的形状转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19028935/