Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript CSS/JS:在文本更改时为内联元素设置动画_Javascript_Html_Css - Fatal编程技术网

Javascript CSS/JS:在文本更改时为内联元素设置动画

Javascript CSS/JS:在文本更改时为内联元素设置动画,javascript,html,css,Javascript,Html,Css,当内联元素的文本更改时,通常情况下其计算的宽度或高度也会更改 通常,使用CSS更改transition属性很简单,例如,添加transition以在悬停时更改元素的背景色 然而,inline元素维度确实很棘手。简单的转换属性不会设置计算的宽度变化的动画 单击此处查看示例:或在下面查看示例: $(“div”)。在(“单击”,函数(){ $(this.text(“虽然我的宽度改变了,但它没有被改变。”); }); div{ 显示:内联块; 背景色:红色; 填充:8px 16px; transiti

内联
元素的文本更改时,通常情况下其计算的
宽度
高度也会更改

通常,使用CSS更改
transition
属性很简单,例如,添加
transition
以在悬停时更改元素的
背景色

然而,
inline
元素维度确实很棘手。简单的
转换
属性不会设置计算的
宽度变化的动画

单击此处查看示例:或在下面查看示例:

$(“div”)。在(“单击”,函数(){
$(this.text(“虽然我的宽度改变了,但它没有被改变。”);
});
div{
显示:内联块;
背景色:红色;
填充:8px 16px;
transition:width 0.3s;//注意,这不会在更改时转换宽度。
}


单击我。
您可以尝试一点jQuery动画:

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

这里是一个。

我想你需要两个元素才能优雅地实现这一点:

$(.inner”)。在(“单击”,函数(){
var$this=$(this);
var$par=$this.parent();
$par.css({
宽度:$par.width()
});
$this.text(“新文本”);
$par.css({
宽度:$this.outerWidth()
});
});
.inner{
显示:内联块;
填充:8px 16px;
空白:nowrap;
}
.外部{
显示:内联块;
过渡:宽度300ms,易于进出;
背景色:红色;
溢出:隐藏;
}

这里有一些文字。
这里有一个更新:


为什么投票被否决?请解释,我会尽力修改。你想如何制作动画,你能用一个例子来解释“这里有一些文本”中的“新文本”将如何显示,因为你不想在显示/隐藏或转换中使用延迟吗?我已经向上投了你的票来否定其他人的反对票,但仍然不清楚你的问题。@grateen.Scripting,看一看:当属性
宽度
值发生变化时,动画就会发生。当视觉宽度改变时不会。尝试使用
addClass
transition
属性时,它的工作方式是:它是否接近您想要的结果?很好,但是当您多次单击它时,会出现一种奇怪的行为,它看起来像一个小故障,要修复它,您可以使用它而不是
$(“div”)。on()
$("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: ""
        });
    })
});