【问题标题】:CSS transition width of line to center线到中心的CSS过渡宽度
【发布时间】:2017-04-28 07:29:11
【问题描述】:

我正在学习 CSS 过渡,我正在尝试使 3 条偏移线将宽度减小到它们各自的中心点。现在宽度转换发生在左侧而不是中心。

这里是Fiddle

如何将每条线的宽度转换为各自的中心点?

代码:

const div = document.getElementById('lines')

div.addEventListener('click', function() {
	var className = div.getAttribute("class");

	if (className != 'open') {
		div.className = 'open';
	} else {
		div.className = '';
	}
})
#lines {
  width: 250px;
  height: 250px;
  position: absolute;
  cursor: pointer;
  transition: .25s ease-in-out;
}
#lines span {
  border: 1px solid black;
  display: block;
  position: absolute;
  height: 15px;
  width: 200px;
  background: #d3531a;
  border-radius: 9px;
  transition: width .25s ease-in-out;
}
#lines span:nth-child(1) {
  top: 0px;
}
#lines span:nth-child(2) {
  top: 18px;
  left: 18px;
}
#lines span:nth-child(3) {
  top: 36px;
  left: 36px;
}

#lines.open span {
  width: 16px;
}
<div id="lines">
  <span></span>
  <span></span>
  <span></span>
</div>

【问题讨论】:

  • 您的 scss 中有语法错误,因此您的跨度没有显示。少了一个分号。请务必在发布之前检查您的演示是否有效。理想情况下,您不会发布 SCSS,而只需发布呈现的 CSS。 jsfiddle.net/w793sps6/3
  • 这很奇怪,跨度出现在小提琴中
  • 不在jsfiddle.net/w793sps6/1 中,您缺少分号,因此 scss 无法编译。
  • 很好,谢谢,我更新了它并在此处修复了代码 sn-p

标签: html css css-transitions


【解决方案1】:

使用transform: scale() 代替width,默认情况下transform-origin 将成为中心。

const div = document.getElementById('lines')

div.addEventListener('click', function() {
	var className = div.getAttribute("class");

	if (className != 'open') {
		div.className = 'open';
	} else {
		div.className = '';
	}
})
#lines {
  width: 250px;
  height: 250px;
  position: absolute;
  cursor: pointer;
  transition: .25s ease-in-out;
}
#lines span {
  border: 1px solid black;
  display: block;
  position: absolute;
  height: 15px;
  width: 200px;
  background: #d3531a;
  border-radius: 9px;
  transition: transform .25s ease-in-out;
}
#lines span:nth-child(1) {
  top: 0px;
}
#lines span:nth-child(2) {
  top: 18px;
  left: 18px;
}
#lines span:nth-child(3) {
  top: 36px;
  left: 36px;
}

#lines.open span {
  transform: scaleX(0);
}
<div id="lines">
  <span></span>
  <span></span>
  <span></span>
</div>

【讨论】:

  • 我发现为了在活动元素上使用transform: scaleX(0);,我需要在非活动元素上使用transform: scaleX(1);,否则动画会导致元素突然消失。
猜你喜欢
  • 2017-04-09
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
相关资源
最近更新 更多