CSS / JS:在文本更改时动态内联元素 [英] CSS/JS: Animate Inline Element Upon Text Change

查看:300
本文介绍了CSS / JS:在文本更改时动态内联元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

inline 元素的文本更改时,通常情况是计算的 width 或<$ c $

$ c> c> CSS,例如,添加 transition 可更改悬停时元素的 background-color



但是, inline 元素尺寸真的很棘手。一个简单的转换属性不会对计算的 width 的变化进行动画处理。


$ b b

点击此处查看示例an: https://jsfiddle.net/mz103/59s42ys4/或查看它:



  $(div)。on(click,function (this).text(虽然我的宽度改变了,它不是aniamted。);});  

  div {display:inline-block; background-color:red; padding:8px 16px; transition:width 0.3s; //注意,这不会在更改时过渡宽度。}  

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< div>点击我。 ; / div>  



inline 元素更改,我们可以为这些更改设置动画吗?

解决方案

这里有一个更新: https://jsfiddle.net/ky3c5Lec/3/

  $(div)。on(click,function(){
//获取当前尺寸动画的开始值
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()没有sth。像Tween.from()
//我们必须将样式重置为初始值
width :sw,height:sh
})。animate({
//然后animate
width:tw,height:th
},function(){
//当动画完成后,我们自己清理后
$ this.css({
width:,height:
});
})
});


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

这篇关于CSS / JS:在文本更改时动态内联元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆