[英]CSS/JS: Animate Inline Element Upon Text Change
When an inline
element's text changes, it is usually the case that its computed width
or height
changes as well. 当
inline
元素的文本发生更改时,通常情况下其计算的width
或height
也会发生变化。
Usually it's trivial to transition
property changes with CSS, for example, adding a transition
to change the background-color
of an element upon hover. 通常,使用CSS
transition
属性更改是微不足道的,例如,添加transition
以在悬停时更改元素的background-color
。
However, inline
element dimensions are really tricky. 但是,
inline
元素尺寸确实很棘手。 A simple transition
property does not animate the change in computed width
. 简单的
transition
属性不会为计算width
的变化设置动画。
View example an by clicking here: https://jsfiddle.net/mz103/59s42ys4/ or viewing it below: 点击此处查看示例: 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>
How, when the text of an inline
element changes, can we animate those changes? 当
inline
元素的文本发生变化时,我们如何设置这些变化的动画?
Here an Update: https://jsfiddle.net/ky3c5Lec/3/ 这里有一个更新: 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: ""
});
})
});
I suppose that you will need two elements to achieve this elegantly: 我想你需要两个元素来优雅地实现这个目标:
$(".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.