我正在创建一个带有一些 CSS 动画的页面(因为我的一些客户不想要 JavaScript 繁重的网站)。所以我有一个元素要设置动画,但根据单击的按钮有 3 种不同的方式:
例子:
<a href="#element">One animation</a>
<a href="#element">Second animation</a>
<a href="#element">Third animation</a>
<div id="element"></div>
我选择元素的方式是使用 :target。但是,如何使用 :target 以三种不同的方式为同一元素设置动画?
这是我现在用于测试目的的 CSS:
#element{
height: 10px;
width: 10px;
border-radius: 0px;
background-color: red;
position: absolute;
left: 440px;
top: 300px;
-webkit-transition-property: height, width, background-color,;
-webkit-transition-duration: 5s;
-webkit-transition-timing-function:ease-out;
}
#element:target{
height: 300px;
width: 500px;
border-radius: 0px;
background-color: blue;
position: absolute;
left: 200px;
top: 200px;
}
所以我基本上想在同一个元素上使用 3 种不同的 :target 样式。这可能吗?
最佳答案
你可以像这样使用 css adjacent(+)
选择器来做到这一点:
HTML:
<a id='first' href="#first">One animation</a>
<a id='second' href="#second">Second animation</a>
<a id='third' href="#third">Third animation</a>
<div id="element" class="force-repaint"></div>
CSS:
#element{
height: 300px;
width: 300px;
border-radius: 0px;
background-color: red;
position: absolute;
left: 300px;
top: 50px;
-webkit-transition-property: height, width, background-color,;
-webkit-transition-duration: .2s;
-webkit-transition-timing-function:ease-out;
}
#first:target + #second + #third + #element {
background: yellow;
}
#second:target + #third + #element{
background: green;
}
#third:target + #element{
background: purple;
}
.force-repaint { -webkit-animation: bugfix infinite 1s; }
@-webkit-keyframes bugfix { from { fill: 0; } to { fill: 0; } }
工作 DEMO
关于css - CSS 中的过渡和目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19077891/