如何在JavaScript中创建一个自动打字功能
在某些情况下,开发者可能想让用户在访问网页时看到动画化的文本内容。这可以通过自动打字来实现。这个功能有助于增强网站的外观,提高整体的用户体验。
自动打字可以用来制作醒目的广告或在用户打字时自动完成文字。它可以被看作是动画,有助于保持注意力,以及简化复杂的信息。这的确是在前端Web项目中实现的一个有用的功能。
前提条件
要继续学习本教程,你需要具备以下条件。
- 对JavaScript有一个基本的了解。
- 对HTML和Bootstrap的理解。
目标
在这篇文章中,我们将使用JavaScript和[jQuery]实现自动打字功能,如下面的视频中所示。
开始使用
我们将使用jQuery和[Immediately Invoked Function Expressions],因为它们很简单。
IIFE的一般语法如下所示。
(function () {
statements;
})();
在上面的例子中,分组操作符阻止了IIFE中的变量被从全局范围访问。
注意,我们将把所有的代码放在一个文件中。
创建JavaScript函数
在你的电脑上创建一个新的文件夹,并给它起任何名字。在这个目录中,生成一个新的文件,并将其命名为index.html 。
我们需要在index.html 文件中添加以下JavaScript代码。我已经用内联评论解释了这些代码片段。
//The function for auto-typing
function autoType(elementClass, typingSpeed, timeout) {
//The target class where the auto-typing will be invoked
var ourClass = $(auto-typing);
//setting the CSS styling for the target class
ourClass.css({
"position": "relative",
"display": "inline-block"
});
//looking for `text-js` containing the text that will be typed out
ourClass = ourClass.find(".text-js");
//remove any trailing spaces
var text = ourClass.text().trim().split('');
//storing the length of text
var amntOfChars = text.length;
//variable to store the text to display
var newString = "";
setTimeout(function () {
//changing the text visibility to visible
ourClass.css("opacity", 1);
//clearing out the text temporarily
ourClass.text("");
//The IIFE where the characters are displayed after computing the typing speed in a for-loop
for (var i = 0; i < amntOfChars; i++) {
(function (i, char) {
setTimeout(function () {
newString += char;
ourClass.text(newString);
}, i * typingSpeed);
})(i, text[i]);
}
}, timeout);
}
function fire(){
//calling the functions with respective arguments (text field, typing speed, and timeout)
autoType(".type-js", 85, 1000);
autoType(".type-js-ii", 200, 2500);
autoType(".type-js-iii", 85, 5800);
autoType(".type-js-iv", 200, 9300);
autoType(".type-js-v", 85, 15000);
}
让我们进一步了解上述JavaScript代码所包含的内容。
autoType() 函数需要三个参数。
elementClass- 自动打字将被调用的目标类。typingSpeed- 这就是打字速度。timeout- 函数启动前的等待时间。autoTyping()
ourClass 变量存储目标类,如下图所示。
ourClass = ourClass.find(".text-js");
我们用下面的代码给元素添加样式。
ourClass.css({
"position": "relative",
"display": "inline-block"
});
接下来,我们寻找text-js 。这是在我们的目标类中找到的一个类。它包含将被打出的文本。此后,我们删除任何尾部的空格。这在下面进行了演示。
ourClass = ourClass.find(".text-js");
//remove any trailing spaces
var text = ourClass.text().trim().split('');
amntOfChars 变量将包含我们文本的长度。然后,我们将在newString 变量中存储要显示的文本。
var amntOfChars = text.length;
//variable to store the text to display
var newString = "";
在setTimeout() 函数中,我们将目标类内容的opacity 从0 设置为1 以使其可见。我们还清除了目标类的文本。
在for 循环中,IIFE以特定索引的index 和text character 作为参数。然后,它通过将索引号乘以打字速度来计算超时。
newString 与提供的text character 的index 连接,直到for 循环结束。
setTimeout(function () {
//changing the text visibility to visible
ourClass.css("opacity", 1);
//clearing out the text temporarily
ourClass.text("");
//The IIFE where the characters are displayed after computing the typing speed in a for-loop
for (var i = 0; i < amntOfChars; i++) {
(function (i, char) {
setTimeout(function () {
newString += char; //concatenation
ourClass.text(newString);
}, i * typingSpeed);
})(i, text[i]);
}
}, timeout);
最后,我们在fire 方法中调用auto-typing() 函数。这显示在下面。
function fire(){
//calling the functions with respective arguments (text field, typing speed, and timeout)
autoType(".type-js", 85, 1000);
autoType(".type-js-ii", 200, 2500);
autoType(".type-js-iii", 85, 5800);
autoType(".type-js-iv", 200, 9300);
autoType(".type-js-v", 85, 15000);
}
HTML和CSS部分
我们将使用下面的HTML代码。
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Auto typing | Eng Ed</title>
<style type="text/css">
.text-js {
opacity: 0;
color: black;
height: auto;
font-family: lucida sans;
}
</style>
</head>
<body onload="fire()" style="background-color: white">
<section style="margin-top: 10vh; padding-left: 15vw" class="pb-5">
<div class="container pb-md-3">
<div class="text-center">
<div class="row">
<div class="col-md-5" style="text-align: left">
<h3 class="mb-4 title" style="color: red">Q & A </h3>
<div class="type-js"><div class="text-js">
Is this Eng-Ed?
</div>
</div>
<br>
<div class="type-js-ii"><div class="text-js">
Yes, why?
</div>
</div><br>
<div class="type-js-iii"><div class="text-js">Tell me more about the community.
</div>
</div><br>
<div class="type-js-iv"><div class="text-js">It is, I mean, it is that--
</div>
</div><br>
<div class="type-js-v"><div class="text-js">Could you please talk faster?
</div>
</div>
</div>
<div class="col-md-7">
<div class="row">
<div class="col-lg-6 mx-lg-auto col-md-12">
<img src="/home/incognito/Documents/section.jpeg" alt="" class="img-fluid mt-lg-5 mt-3">
</div>
</div>
</div>
</div>
</div>
</section>
</body>
在<head> 部分,我们将text color 设为black ,font 设为Lucida sans ,text height 设为auto 。
<style type="text/css">
.text-js {
opacity: 0;
color: black;
height: auto;
font-family: lucida sans;
}
</style>
在<body> 标签中,我们在加载时调用fire() 函数。
<body onload="fire()" style="background-color: white">
Bootstrap 5 是用来做造型的。
在上面的代码中,我们使用下面的代码导入了Bootstrap 。
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
记住要导入jQuery ,否则自动打字功能将无法工作。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
完整的代码
完成上述步骤后,我们可以保存我们的文件,然后在浏览器中查看它。你的最终代码应该如下所示。
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Auto typing | Eng Ed</title>
<style type="text/css">
.text-js {
opacity: 0;
color: black;
height: auto;
font-family: lucida sans;
}
</style>
</head>
<body onload="fire()" style="background-color: white">
<section style="margin-top: 10vh; padding-left: 15vw" class="pb-5">
<div class="container pb-md-3">
<div class="text-center">
<div class="row">
<div class="col-md-5" style="text-align: left">
<h3 class="mb-4 title" style="color: red">Q & A </h3>
<div class="type-js"><div class="text-js">
Is this Eng-Ed?
</div>
</div>
<br>
<div class="type-js-ii"><div class="text-js">
Yes, why?
</div>
</div><br>
<div class="type-js-iii"><div class="text-js">Tell me more about the community.
</div>
</div><br>
<div class="type-js-iv"><div class="text-js">It is, I mean, it is that--
</div>
</div><br>
<div class="type-js-v"><div class="text-js">Could you please talk faster?
</div>
</div>
</div>
<div class="col-md-7">
<div class="row">
<div class="col-lg-6 mx-lg-auto col-md-12">
<img src="/home/incognito/Documents/section.jpeg" alt="" class="img-fluid mt-lg-5 mt-3">
</div>
</div>
</div>
</div>
</div>
</section>
</body>
<script>
//The function for auto-typing
function autoType(elementClass, typingSpeed, timeout) {
//The target class where the auto-typing will be invoked
var ourClass = $(elementClass);
//setting the CSS styling for the target class
ourClass.css({
"position": "relative",
"display": "inline-block"
});
//looking for `text-js` containing the text that will be typed out
ourClass = ourClass.find(".text-js");
//remove any trailing spaces
var text = ourClass.text().trim().split('');
//storing the length of text
var amntOfChars = text.length;
//variable to store the text to display
var newString = "";
setTimeout(function () {
//changing the text visibilty to visible
ourClass.css("opacity", 1);
//clearing out the text temporarily
ourClass.text("");
//The IIFE where the characters are displayed after computing the typing speed
for (var i = 0; i < amntOfChars; i++) {
(function (i, char) {
setTimeout(function () {
newString += char;
ourClass.text(newString);
}, i * typingSpeed);
})(i, text[i]);
}
}, timeout);
}
function fire(){
//calling the functions with respective arguments
autoType(".type-js", 85, 1000);
autoType(".type-js-ii", 200, 2500);
autoType(".type-js-iii", 85, 5800);
autoType(".type-js-iv", 200, 9300);
autoType(".type-js-v", 85, 15000);
}
</script>
</html>
结语
本教程向你展示了如何使用JavaScript和jQuery创建一个自动打字功能。我们分析了JavaScript代码并确定了它的工作原理。我希望你获得了一些见解,并将其应用于你的下一个项目。