jquery - CSS宽度动画方向

标签 jquery html css animation css-animations

我正在尝试为 span 元素的宽度设置动画。

这就是我的 HTML + CSS + jQuery 的样子:

.tt {
	position: absolute;
	width: 55px;
	height: 3px;
	background-color: #999997;
	top: 0;
	right: 10px;
	opacity: 0;	
}

.tt-expand {
	width: 55px;
	opacity: 1;	
	animation: 1s ease tt-expand;  
}

@keyframes tt-expand {

	0% {
	width: 0;
	}
	100% {
	width: 55px;
	}

}

.relative {
    display: inline-block;
    position: relative;
    padding: 20px 28px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script>
jQuery(document).ready(function($) {

setTimeout(function(){
	$( '.tt' ).addClass( 'tt-expand' );
}, 1000 );

});
</script>

<div class="relative">
		<h2>Heading</h2>
		<span class="tt"></span>
</div>

问题:

线条从从右到左动画。

首选结果:

理想情况下,线条应该从从左到右

Animation Illustration

问题

如何让 SPAN 元素的宽度从左到右进行动画处理?

谢谢。

最佳答案

当您使用 right 定位元素时,其 width 从右侧增长,因此您需要将其定位在左侧,此处使用 CSS Calc 完成, left: calc(100% - 10px - 55px);

.tt {
  position: absolute;
  width: 55px;
  height: 3px;
  background-color: #999997;
  top: 0;
  left: calc(100% - 10px - 55px);
  opacity: 0;
}

.tt-expand {
  width: 55px;
  opacity: 1;
  animation: tt-expand 1s ease;
}

@keyframes tt-expand {
  0% {
    width: 0;
  }
  100% {
    width: 55px;
  }
}

.relative {
  display: inline-block;
  position: relative;
  padding: 20px 28px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script>
  jQuery(document).ready(function($) {

    setTimeout(function() {
      $('.tt').addClass('tt-expand');
    }, 1000);

  });
</script>

<div class="relative">
  <h2>Heading</h2>
  <span class="tt"></span>
</div>


如果出于某种原因无法使用 CSS Calc,您可以这样做,在其中设置宽度和右侧值的动画

.tt {
  position: absolute;
  width: 55px;
  height: 3px;
  background-color: #999997;
  top: 0;
  right: 10px;
  opacity: 0;
}

.tt-expand {
  width: 55px;
  opacity: 1;
  animation: tt-expand 1s ease;
}

@keyframes tt-expand {
  0% {
    width: 0;
    right: 65px;
  }
  100% {
    width: 55px;
    right: 10px;
  }
}

.relative {
  display: inline-block;
  position: relative;
  padding: 20px 28px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script>
  jQuery(document).ready(function($) {

    setTimeout(function() {
      $('.tt').addClass('tt-expand');
    }, 1000);

  });
</script>

<div class="relative">
  <h2>Heading</h2>
  <span class="tt"></span>
</div>

关于jquery - CSS宽度动画方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43293654/

相关文章:

javascript - 在元素之间画线

html - Rotativa Pdf 生成不遵守 HTML 字符间距

javascript - 内容可编辑不使用 localStorage 保存

php - 使用ajax发送变量

javascript - JQuery URL 验证器

c# - Gridview 的 Jquery 和更新面板不起作用

html - 滚动时背景高度全屏

javascript - Promise 未在 .each() 循环中解决

带有 CSS3 过渡效果的 HTML 翻页卡片

css - 如何在 div 的样式属性中引用背景图像?