我有一些水平线,使用div
元素制作。它们都通过使用CSS来设置过渡,并使用JS来设置新width
来设置动画。这是我当前的代码和结果:
.HTML:
<div style="bottom: 10%;" class="lines-horizontal"></div>
<div style="bottom: 20%;" class="lines-horizontal"></div>
<div style="bottom: 30%;" class="lines-horizontal"></div>
<div style="bottom: 40%;" class="lines-horizontal"></div>
<div style="bottom: 50%;" class="lines-horizontal"></div>
<div style="bottom: 60%;" class="lines-horizontal"></div>
<div style="bottom: 70%;" class="lines-horizontal"></div>
<div style="bottom: 80%;" class="lines-horizontal"></div>
<div style="bottom: 90%;" class="lines-horizontal"></div>
<div style="bottom: 100%;" class="lines-horizontal"></div>
.CSS:
.lines-horizontal {
position: relative;
width: 0%;
transition: width 2s;
height: 5px;
background-color: black;
opacity: 0.2;
z-index: -5;
margin-bottom: 10px;
}
.JS:
var horizontalLines = document.getElementsByClassName("lines-horizontal")
for (var hLines = 0; hLines < horizontalLines.length; hLines++) {
horizontalLines[hLines].style.width = "100%"
}
结果:https://jsfiddle.net/u5Lfu11j/4/
这里的问题是线条从左侧开始动画化。就像有一个transform-origin
属性一样,除了过渡/动画之外,我有什么方法可以做同样的事情吗?我希望能够将线条设置为从中心开始并向外扩展。
>margin: auto
将为您提供所需的从中心转换:
.lines-horizontal {
position: relative;
width: 0%;
transition: width 2s;
height: 5px;
background-color: black;
opacity: 0.2;
z-index: -5;
margin: 0px auto 10px auto;
}
https://jsfiddle.net/u5Lfu11j/22/
一个更简单的解决方案是只使用一个元素和渐变背景,然后在没有 JS的情况下对背景大小进行动画处理:
.box {
height:200px;
background-image:linear-gradient(rgba(0,0,0,0.2) 30%,transparent 30%);
background-size:0% 20px;
background-position:50% 0;
background-repeat:repeat-y;
animation:anim 2s forwards;
}
@keyframes anim {
from{
background-size:0% 20px;
}
to {
background-size:100% 20px;
}
}
<div class="box">
</div>
您还可以将它们视为不同的元素,以防您想要以不同的方式对它们进行动画处理:
.line {
height: 15px;
margin-bottom: 15px;
background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2));
background-size: 0% 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
}
.line:nth-child(1) {
animation: anim 2s forwards;
}
.line:nth-child(2) {
animation: anim 2s forwards 0.5s;
}
.line:nth-child(3) {
animation: anim 2s forwards 1s;
}
@keyframes anim {
from {
background-size: 0% 100%;
}
to {
background-size: 100% 100%;
}
}
<div>
<div class="line">
</div>
<div class="line">
</div>
<div class="line">
</div>
</div>