CSS / JS:文本更改时动画内联元素

时间:2016-02-11 03:05:27

标签: javascript html css

inline元素的文字发生变化时,通常情况下其计算的widthheight也会发生变化。

通常使用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>
&#13;
&#13;
&#13;

如果inline元素的文字发生变化,我们可以为这些更改设置动画吗?

3 个答案:

答案 0 :(得分:2)

此处有更新: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: ""
        });
    })
});

答案 1 :(得分:1)

您可以尝试一些jQuery动画:

function changeText(el) {
    el.animate(
    {
        opacity: 0
    }, 
    {
        duration: 'slow', 
        complete: function () {
            $(this).text('New Text');
            $(this).animate({opacity: 1}, 'slow');
        }
    });  
}

这是fiddle

答案 2 :(得分:1)

我认为你需要两个元素来实现这一目标:

$(".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>