[英]CSS/JS: Animate Inline Element Upon Text Change
当inline
元素的文本发生更改时,通常情况下其计算的width
或height
也会发生变化。
通常,使用CSS transition
属性更改是微不足道的,例如,添加transition
以在悬停时更改元素的background-color
。
但是, inline
元素尺寸确实很棘手。 简单的transition
属性不会为计算width
的变化设置动画。
点击此处查看示例: https : //jsfiddle.net/mz103/59s42ys4/或查看以下内容:
$("div").on("click", function() { $(this).text("Although my width changes, it is not aniamted."); });
div { display: inline-block; background-color: red; padding: 8px 16px; transition: width 0.3s; // Notice, this doesn't transition the width upon change. }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Click me.</div>
当inline
元素的文本发生变化时,我们如何设置这些变化的动画?
这里有一个更新: https : //jsfiddle.net/ky3c5Lec/3/
$("div").on("click", function() {
//get the current Dimensions, as Start-value for the animation
var $this = $(this),
sw = $this.width(),
sh = $this.height();
$this.text("New text");
var tw = $this.width(),
th = $this.height();
$this.css({
//since jQuery.animate() doesn't have sth. like Tween.from()
//we have to reset the styles to the initial values
width: sw, height: sh
}).animate({
//and then animate
width: tw, height: th
}, function(){
//and when the animation is done, we clean up after ourselves
$this.css({
width: "", height: ""
});
})
});
您可以尝试一些jQuery动画:
function changeText(el) {
el.animate(
{
opacity: 0
},
{
duration: 'slow',
complete: function () {
$(this).text('New Text');
$(this).animate({opacity: 1}, 'slow');
}
});
}
这是一个小提琴 。
我想你需要两个元素来优雅地实现这个目标:
$(".inner").on("click", function() { var $this = $(this); var $par = $this.parent(); $par.css({ width: $par.width() }); $this.text("New text"); $par.css({ width: $this.outerWidth() }); });
.inner { display: inline-block; padding: 8px 16px; white-space: nowrap; } .outer { display: inline-block; transition: width 300ms ease-in-out; background-color: red; overflow: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="outer"> <div class="inner">Here's some text.</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.