javascript - CSS 从中心过渡

标签 javascript html css css-transitions css-animations

我有一些使用 div 元素制作的水平线。所有这些都通过使用 CSS 来设置过渡和 JS 来设置新的宽度来实现动画。这是我当前的代码和结果:

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/

关于javascript - CSS 从中心过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49224402/

相关文章:

html - 如何在不重启的情况下移动视频元素?

javascript - 如何像触摸光标一样查看图像?

javascript - promise 创建中的 "this"是什么?

javascript - 如何使用 JavaScript 清除 div 的内容?

javascript - Slider FileReader JS 多图上传(递增索引)

html - 我如何防止 CSS 样式影响我网站的其他部分?

html - 在 WordPress 中将图像缩放到 div 的 100% 高度

javascript - 如何创建自定义 polymer 元素的方法并在主应用程序中调用它?

html - 从上下文中获取对 Canvas 元素的引用?

javascript - 删除按钮不起作用