[英]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.