CSS/JS: Animate Inline Element Upon Text Change

前端 未结 3 1623
再見小時候
再見小時候 2021-01-06 03:15

When an inline element\'s text changes, it is usually the case that its computed width or height changes as well.

Usually it\'

相关标签:
3条回答
  • 2021-01-06 04:02

    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>

    0 讨论(0)
  • 2021-01-06 04:04

    Here an Update: 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: ""
            });
        })
    });
    
    0 讨论(0)
  • 2021-01-06 04:16

    You could try a little bit of jQuery animation:

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

    Here is a fiddle.

    0 讨论(0)
提交回复
热议问题