简介:本文是一个前端案例的讲解,关于如何用html+css+js制作出逐渐显示出文字的效果,这个效果可以帮助大家在新人面前装一波。
效果就是这个样子的,这个文本框里面的内容,不是我输入的,是自己自动慢慢显示到文本框中的。
这个东西看似很新奇,但是实现的原理还是非常简单的,就是提前把文本写好,写好之后,然后设计一个函数,可以慢慢输出字符串的,然后再利用setInterval来运行这个函数,运行过程中设置一个合适的时间间隔就可以了。
具体的函数如下:其实type里面加一个参数更好,这样的话可以,更通用,但是了,之前测试的时候这样写了但是出问题了,挺奇怪的。写高耦合代码也是有好处的,老板不敢随便把你开了。
后面还可以加上音效,打字的音效,这样的话会有一种独特的效果。
function type()
{
editor1.focus();
t += text[i];
// console.log(t)
i ++;
editor1.innerHTML = "<h1>" + t + "</h1>";
if (i >= text.length){
clearInterval(timer)
i = 0;
text="";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>开始了</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.css" />
<style>
body{
padding: 100px 200px;
}
.form-control{
min-height:500px;
margin: 30px;
border-color: skyblue;
}
#editor1 {
height: 500px;
display: inline-block;
}
.music{
display: none;
}
img{
width: 250px;
height: 250px;
}
#btn2{
display: none;
}
#btn3{
display: none;
}
.button.red{
margin-left: 90%;
width: 100px;
height: 50px;
box-shadow: 0 1px 2px #8fcaee inset,0 -1px 0 #497897 inset,0 -2px 3px #8fcaee inset;
background: -webkit-linear-gradient(top,#42a4e0,#2e88c0);
background: -moz-linear-gradient(top,#42a4e0,#2e88c0);
background: linear-gradient(top,#42a4e0,#2e88c0);
}
</style>
<link rel="icon" href="./logo.ico">
<link href="css/buttonStyle.css">
</head>
<body>
<div id="editparent">
<div><img src="./images/img1.png"></img></div>
<!-- 编辑器控制按钮 -->
<div id='editControls' style='text-align:center; padding:5px;'>
<h1>回望2022年</h1>
</div>
<!-- div负责文本内容的显示-->
<div id="editor1" class='form-control' contenteditable >
<h3></h3>
</div>
<!-- 打字音效 -->
<audio controls src="/radio/radio5.mp3" id="music3" class="music">
Your browser does not support the
<code>audio</code> element.
</audio>
</div>
<button id="btn1" type="button" class="button red"><b>开始</b></button>
<script>
// 默认文本聚焦的
var editor1 = document.getElementById("editor1");
editor1.focus();
var i = 0;
var text = ""
var text1 = "#include<stdio.h> int main() { printf(\"Hello World 2023\"); return 0;}";
var t = ""
var timer = null;
var btn1 = document.getElementById("btn1");
// 输出字的函数
function type()
{
editor1.focus();
t += text[i];
// console.log(t)
i ++;
editor1.innerHTML = "<h1>" + t + "</h1>";
if (i >= text.length){
clearInterval(timer)
i = 0;
text="";
}
}
btn1.onclick = function(){
console.log("开始");
editor1.innerHTML = "";
text = text1;
timer = setInterval(type, 170);
let audioPlay = document.getElementById("music3").play();
btn1.style.display = "none";
}
</script>
</body>
</html>