如何使用css动画从中心增加边界线

how to increase border line from the center using css animation

本文关键字:增加 边界线 何使用 css 动画      更新时间:2023-09-26

我在玩CSS动画,我想知道是否有一种方法可以在加载页面时自动增加一条垂直线(具有一定高度)的长度。理想情况下,我希望垂直线从中间增长,从顶部和底部增长到特定的高度。到目前为止,我只能让它从上到下增加长度。这是我的:

.vertical-line {
	margin-left: 100px;
	background: red;
	width: 8px;
	border-radius: 4px;
	animation: grow 4s forwards;
}
@keyframes grow {
	0% {
		height: 10px;
	}
	100% {
		height: 100px;
	}
}
<!DOCTYPE html>
<html>
	<head>	
		<title>Creating Vertical borders using animation/javascript</title>	
	</head>
	<body>
		<div class="vertical-line"></div>
	</body>
</html>

代码的错误之处在于您只是增加了高度。为了在增加高度的同时在两侧生长,必须将该元素移向另一侧
示例:如果你的高度增加了100px,那么你必须反向移动50px

CSS:

#cool
{
height:10px;
width:10px;
border-radius:4px;
margin-left:10%;
background-color:#431;
margin-top:20%;
animation:grow 3s forwards;
position:relative;
}
@keyframes grow
{
0% {
    height: 0px;
    top:0;
}
100%{
    height: 200px;
    top:-100px;
}
}
</style>

HTML:

<div id=cool>
</div>
</body>

对于高度100px,将元素移动到顶部-50px。拿了一半,因为显示了两边的增长。如果顶部为-100px,那么它将从底部生长。
我希望这能帮助

实现这一点的一种方法是将线的初始位置设置在最中心,然后使其向视口的顶部和底部延伸。

.myLine {
  position: absolute;
  left: 50vw;
  top: 50vh;
  width: 1px;
  height: 1px;
}

然后,您可以通过JavaScript添加一个类extended,该类可以更改位置和高度,从而使其看起来从中心垂直延伸。

.extended {
    top: 0vh;
    bottom: 100vh;
    height: 100%;
    transition: all 3s ease;
}

使用JavaScript,正如我在这里所做的那样,您可以设置一个短暂的超时,并在超时结束后添加类。

var el = document.querySelector('.myLine');
setTimeout(function() {
 el.classList.add('extended');
}, 300);

请参阅我的示例代码笔。

试试这个,

<div class="vertical-line"></div>
<style>
    .vertical-line {
        position: absolute;
        top: 0;
        border: 5px solid red;
        width: 10px;
        border-radius: 4px;
        animation: grow 3s infinite alternate;
    }
    @keyframes grow {
        0% {
            width: 0px;
            height: 0px;
        }
        100% {
            width: 20px;
            height: 100%;
        }
    }
</style>