首页 > 解决方案 > 如何使用按钮单击平滑淡入淡出切换文本?

问题描述

我有以下代码 -

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function toggleText(){
    if ($("#txt-1").css("display") != "none") {
        $("#txt-1").css("display", "none");
        $("#txt-2").css("display", "block");
        $("#txt-3").css("display", "none");
    } else if ($("#txt-2").css("display") != "none") {
        $("#txt-1").css("display", "none");
        $("#txt-2").css("display", "none");
        $("#txt-3").css("display", "block");
    } else {
        $("#txt-1").css("display", "block");
        $("#txt-2").css("display", "none");
        $("#txt-3").css("display", "none");
    }
};
</script>
</head>
<body>

<button onclick="toggleText()">Toggle</button>

<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>
<p id="txt-3" style="display: none;">See you soon!</p>

</body>
</html>

它在按钮单击时切换文本 在此处输入图像描述

我正在寻找的是,在文本之间进行平滑过渡(也许淡入淡出)。我不确定是否写 aCSSjQuery.

我尝试的是写一个CSS类-

.smooth-fade {
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

并将此类名称提供smooth-fade给所有h1标签。它不起作用,执行此任务的最佳解决方法是什么?

标签: javascripthtmljquerycss

解决方案


您可以为此使用 jquery:

  $( "#txt-1" ).fadeOut( "slow", function() {
     $("#txt-2").fadeIn();
  });

首先淡出你想要的元素,然后使用回调函数淡入其他元素。

function toggleText(){
  $( "#txt-1" ).fadeOut( "slow", function() {
     $("#txt-2").fadeIn();
  });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button onclick="toggleText()">Toggle</button>

<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>


推荐阅读