javascript - 如何使用按钮单击平滑淡入淡出切换文本?
问题描述
我有以下代码 -
<!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>
我正在寻找的是,在文本之间进行平滑过渡(也许淡入淡出)。我不确定是否写 aCSS
或jQuery
.
我尝试的是写一个CSS
类-
.smooth-fade {
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
并将此类名称提供smooth-fade
给所有h1
标签。它不起作用,执行此任务的最佳解决方法是什么?
解决方案
您可以为此使用 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>
推荐阅读
- html - 如何让我的十字架完全适合周围的容器?
- mapstruct - 我可以使用 MapStruct 控制映射顺序吗?
- mysql - 2006, 'SSL 连接错误:未知错误号'
- python - 与 dunder 方法 __dict__ 相比,dict() 做了什么?
- sass - Node-Sass 在编译时包含 @use 指令
- java - 如何证明方法在类图 (UML) 中是同步的?
- javascript - 关闭清除下拉菜单
- python - 第一次尝试将烧瓶应用程序上传到heroku时出现Applicationerror
- python - 快速排序 Python 递归 - 递归函数是如何工作的
- python - 如何将对象插入到MongoDB中的对象中