我正在尝试为 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>
问题:
线条从从右到左动画。
首选结果:
理想情况下,线条应该从从左到右
问题
如何让 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/