CSS/JS:文本更改时对内联元素进行动画处理

2023-12-01

When an inline元素的文本发生变化,通常情况是它的计算width or height也发生变化。

通常这是微不足道的transition属性随 CSS 改变,例如添加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: ""
        });
    })
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSS/JS:文本更改时对内联元素进行动画处理 的相关文章

随机推荐