简体   繁体   中英

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.

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.

However, inline element dimensions are really tricky. A simple transition property does not animate the change in computed width .

View example an by clicking here: https://jsfiddle.net/mz103/59s42ys4/ or viewing it below:

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

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: ""
        });
    })
});

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 .

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM