by Ashish Nandan Singh
通过Ashish Nandan Singh
DOM stands for Document Object Model. It’s nothing more than the block level diagram of all the HTML elements loaded on the page when a browser loads a web page. It is presented as a tree of objects which are HTML elements. Look at the image below and you may get a better idea.
DOM代表文档对象模型。 它不过是浏览器加载网页时页面上加载的所有HTML元素的方框图。 它以HTML元素的对象树的形式呈现。 看下面的图片,您可能会得到一个更好的主意。
A nice clean block diagram of your ugly .html file — isn’t that great! But now you are thinking, how does this help me? What’s the use case? Why do I need to know this?
丑陋的.html文件的一个漂亮干净的框图-并不是那么好! 但是现在您正在思考,这对我有什么帮助? 用例是什么? 为什么我需要知道这一点?
To put it simply, the DOM enables you to bring dynamics to your static website. With the use of the DOM, you can do a bunch of useful things on the webpage like:
简而言之,DOM使您能够为静态网站带来动力。 使用DOM,您可以在网页上做很多有用的事情,例如:
And this is exactly what you will learn throughout the course of this article.
这正是您将在本文中学习的全部内容。
To give you an idea of what we will achieve by the end of this article, check out this link.
为了让您大致了解到本文结尾处将实现的目标,请查看此链接 。
We will build a simple color guessing game. Every time the game is started, a random RGB color code will be selected. Depending on the mode of the game, we will have three (easy) or six (hard) options or color blocks on the screen to choose from. Every time an incorrect color block is selected, the block will disappear until the user selects the correct color (or its the last option left).
我们将构建一个简单的颜色猜测游戏。 每次游戏开始时,都会选择一个随机的RGB颜色代码。 根据游戏的模式,我们将在屏幕上提供三个(简单)或六个(硬性)选项或色块供您选择。 每次选择了不正确的颜色块,该块都会消失,直到用户选择了正确的颜色(或其最后一个选项)为止。
Here’s a rough diagram of what we would be building:
这是我们将要构建的粗略图:
This is something I learnt while I was taking a course from Colt Steele, phenomenal trainer when it comes to teaching basic concepts. You all should check out his videos on Udemy’s YouTube channel.
这是我在从Colt Steele上课时学到的,而Colt Steele在讲授基本概念方面是一位出色的培训师。 大家都应该在Udemy的YouTube频道上观看他的视频。
We’ll start by creating a simple web boiler plate, which will be compromised of index.html, app.css, and app.js files. Let’s see how these files look when we’re starting out.
我们将从创建一个简单的Web样板开始,该样板将破坏index.html,app.css和app.js文件。 让我们看看刚开始时这些文件的外观。
But first, please note: just to keep it simple for anyone who is reading this without any prior development experience, I will keep showing the source code whenever we change something major.
但首先,请注意:只是为了使没有任何先验开发经验的任何人都可以简单阅读,只要我们对主要内容进行了更改,我都会一直显示源代码。
index.html
index.html
<!DOCTYPE html><html>
<head><title>Color Game</title><link rel="stylesheet" type="text/css" href="app.css"></head>
<body>
<h1>The Great<br><span id="colorDisplay">RGB</span><br>Color Game</h1>
<div id="stripe">
<button id="reset">New Colors</button><span id="message"></span><button class="mode">Easy</button><button class="mode selected">Hard</button>
</div>
<div id="container">
<div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div>
</div>
<script type="text/javascript" src="app.js"></script></body></html>
This is as simple as it gets. We can simply segregate the entire webpage in three primary blocks.
这很简单。 我们可以简单地将整个网页分为三个主要部分。
First we have the header section, which has the text and may contain some other information if you want to add it in there.
首先,我们有标题部分,其中包含文本,如果您想在其中添加内容,则可能包含其他信息。
Next is the control panel, which has buttons to reset the game and to switch between the game modes.
接下来是控制面板,其中包含用于重置游戏和在游戏模式之间切换的按钮。
Third — and the most interesting part — is the main game area, which has six divs. These divs serve as the options for every random RGB color code which can be selected by some fancy logic (which we will see in a while).
第三,也是最有趣的部分,是主游戏区域,它具有六个div。 这些div用作每种随机RGB颜色代码的选项,可以通过一些特殊的逻辑来选择(我们将在一段时间内看到)。
app.css
app.css
body {
background-color: #232323;margin: 0;font-family: "Montserrat", "Avenir";}
h1 {
text-align: center;line-height: 1.1;font-weight: normal;color: white;background: steelblue;margin: 0;text-transform: uppercase;padding: 20px 0;}
#container {
margin: 20px auto;max-width: 600px;}
.square {
width: 30%;background: purple;padding-bottom: 30%;float: left;margin: 1.66%;border-radius: 15%;transition: background 0.6s;-webkit-transition: background 0.6s;-moz-transition: background 0.6s;}
Some basic styles have been added for the body, text, and squares that serve as the game options.
已为主体,文本和正方形添加了一些基本样式,以用作游戏选项。
app.js
app.js
var numSquares = 6;var colors = [];var pickedColor;var squares = document.querySelectorAll(".square");var resetButton = document.querySelector("#reset");var modeButtons = document.querySelectorAll(".mode");
We have stored all the HTML elements in the form of variables. This will help us perform some actions by adding events to each of these variables, and by calling them inside various logic functions we will create during this article.
我们以变量的形式存储了所有HTML元素。 这将通过向每个变量添加事件,并在本文将要创建的各种逻辑函数中调用事件来帮助我们执行某些操作。
In fact, let’s break each of these variables down and see what their significance is:
实际上,让我们分解每个变量,看看它们的意义是什么:
The numSquares variable stores the number of squares that will be available in the game as per the mode. For simplicity’s sake, I have hard coded the value to be six always — we can come back to this and add some logic to keep it changing.
numSquares变量根据模式存储游戏中可用的平方数。 为简单起见,我将值硬编码为始终为6 -我们可以返回到此值并添加一些逻辑以使其保持不变。
colors is an empty array which contains the random six or three RGB color code generated every time the game is reset or the mode is changed.
colors是一个空数组,其中包含每次重置游戏或更改模式时生成的随机六或三个RGB颜色代码。
pickedColor is the color/option block selected by the user upon every click.
pickColor是用户每次单击时选择的颜色/选项块。
squares is an array of all the squares on the page that are available as options. This array may have three or six elements depending on the mode of the game.
squares是页面上所有可选项的正方形的数组。 该阵列可以具有三个或六个元素,具体取决于游戏的模式。
The reset variable is the “new game” button in the control panel.
重置变量是控制面板中的“新游戏”按钮。
modeButtons is again an array which has easy and hard mode buttons in it.
modeButtons还是一个数组,其中包含简单和困难模式按钮。
If you have followed up to this point, here you should have a pretty basic version of this game. You may open the index.html file in any browser and check it out. All right, so now that we have the ground set, let’s get to the serious stuff.
如果您已经跟进了这一步,那么这里应该有这个游戏的基本版本。 您可以在任何浏览器中打开index.html文件并将其检出。 好吧,现在我们有了基础,让我们开始认真的研究。
In this section, we will mostly be working with the JavaScript file and a few times with the CSS file.
在本节中,我们将主要使用JavaScript文件,并使用CSS文件几次。
Generating random colours
生成随机颜色
Our first goal will generating random colors every time the game is started or restarted or the mode is changed. Let’s see how can do that.
我们的第一个目标是每次游戏启动或重新启动或更改模式时生成随机颜色。 让我们看看如何做到这一点。
To understand the underlying principle of generating anything randomly, we should start with a hard coded array of six RGB color codes. Let’s try to set those colors as the background colors of the six squares/options available on the webpage.
要了解随机生成任何东西的基本原理,我们应该从六个RGB颜色代码的硬编码数组开始。 让我们尝试将这些颜色设置为网页上可用的六个正方形/选项的背景颜色。
var colors = [
"rgb(255, 0, 0)", "rgb(255, 0, 255)", "rgb(255, 225, 0)", "rgb(255, 0, 255)", "rgb(0, 255, 255)", "rgb(0, 255, 0)"
];
var squares = document.querySelectorAll(.squares);
for (i=0; i<squares.length; i++) {squares.style.backgroundColor = colors[i]}
If you add this to the app.js file and you refresh the browser, you will see that each square is now a unique color.
如果将其添加到app.js文件并刷新浏览器,您将看到每个正方形现在都是唯一的颜色。
You might notice that the buttons are not yet styled, but leave that for now. We will come to that part later on.
您可能会注意到按钮尚未设置样式,但请立即保留。 稍后我们将介绍这一部分。
So all we need is event listeners enabled on each option/color block listening for click events. The easiest way to do that is — again you guessed it right — by looping through the array of squares. This loop would look similar to that which was used to style the background of the color blocks. Let’s take a look at the code:
因此,我们需要的是在每个选项/颜色块上启用事件侦听器,以侦听单击事件。 最简单的方法是-再次猜对了-通过遍历正方形数组。 该循环看起来类似于用于对色块的背景进行样式设置的循环。 让我们看一下代码:
for(i=0; i<= squares.length; i++) { squares[i].addeventListeners('click', function() { alert('option was clicked'); });}
Now every time you click on any block you will get this alert message from the browser. That was easy! Now our options are receptive, and they are responding to user input. All we need to do now is define the logic that tells what happens if the color picked by the game and that chosen by the user are the same.
现在,每次单击任何块时,您都会从浏览器中收到此警报消息。 那很简单! 现在,我们的选项可以接受,它们正在响应用户输入。 现在我们需要做的就是定义逻辑,该逻辑告诉游戏选择的颜色和用户选择的颜色相同时会发生什么。
By now you may already have the solution if you have paid attention to the above parts carefully. So let’s see how we can do it.
如果您已经仔细注意了以上部分,那么现在您可能已经有了解决方案。 因此,让我们看看如何做到这一点。
Let’s explore the possibilities we have with our options/color boxes being receptive and responding back. We can conduct a small test and see if the two colors match or not. Very soon we will have randomly generated colors every time we refresh the page or every time we reset the game or change the mode of game. But for now, we will practice with the set of six RGB color codes we have assigned in the file.
让我们探讨一下我们的选项/颜色框可以接受并做出回应的可能性。 我们可以进行一次小测试,看看两种颜色是否匹配。 很快,每次刷新页面或每次重置游戏或更改游戏模式时,我们都会随机生成颜色。 但是现在,我们将使用在文件中分配的六组RGB颜色代码进行练习。
Let’s look at some code and then I would break it down for you.
让我们看一些代码,然后为您分解。
for(i=0; i<= squares.length; i++) { squares[i].addeventListeners('click', function() { //if correct block is clicked do something.... //if wrong block is clicked do something.... });}
As you already may know, we will be using a simple if-else block.
您可能已经知道,我们将使用一个简单的if-else 块。
pickedColor = colors[3];for (i=0; i <= squares.length; i++) { //apply background colour to all the squares... squares[i].style.backgroundColor = colors[i] //enable click event on each square..... squares[i].addEventListener('click', function() {
//if the user selected the right colour.... var clickedColor = this.style.backgroundColor;
//check if the selected colour matches the default colour...
if(pickedColor === clickedColor) { changeColors(pickedColor); } //if the user user selected wrong colour.... else { this.style.backgroundColor = "#232323"; messageDisplay.text = "Wrong Choice!"; } })};
I know — it’s a lot of code. But let’s see what it really means:
我知道-这是很多代码。 但是,让我们看看它的真正含义:
We start with defining what the default color picked by the game will be, with the variable pickedColour.
我们首先使用变量pickColour定义游戏选择的默认颜色。
Then we run our for loop which lets us go through the array of color blocks/options.
然后我们运行for循环 ,让我们遍历颜色块/选项的数组。
Then we enable the click events on each and every color bock/option. We do this using a callback function. This function does nothing but select the background color of the selected color block/option simply by assigning it to the variable called clickedColour.
然后,我们在每个颜色框/选项上启用单击事件 。 我们使用回调函数执行此操作。 该函数仅将所选色块/选项的背景色分配给名为clickedColour的变量,就不会执行任何操作。
We can do this easily using the if else block. If the choice is correct, then do this, or else do something else
我们可以使用if else块轻松地做到这一点。 如果选择正确,则执行此操作,否则执行其他操作
function changeColors(color) { for (i=0; i <= squares.length; i++) { squares[i].style.backgroundColor = color; messageDisplay.text = "You are good at guessing!"; }}
This function goes through the array of color blocks/options and resets the background color to be that of the selected color or the default color.
此功能遍历颜色块/选项的阵列,并将背景色重置为所选颜色或默认颜色。
In case the colors are not the same, we simply set the current selection’s background color to be that of the webpage.
如果颜色不同,我们只需将当前选择的背景色设置为网页的背景色即可。
else { this.style.backgroundColor = "#232323"; messageDisplay.text = "Wrong Choice!";}
Alright now that we have the main game set, we just need to worry about minimal design issues and adding the functionality into the control panel.
现在我们有了主要的游戏设置,我们只需要担心最小的设计问题并将功能添加到控制面板中即可。
But first let’s look at what the code folder looks like at this point if you have followed all the steps correctly:
但是首先让我们看看如果正确地执行了所有步骤,此时代码文件夹是什么样的:
index.html
index.html
app.css
app.css
app.js
app.js
All is well. But now we need to create new randomly generated RGB color codes in our game that are not the same set of colours that would be assigned in the color blocks/options.
一切都很好。 但是现在我们需要在游戏中创建随机生成的新RGB颜色代码,这些颜色代码与在颜色块/选项中分配的颜色集不同。
If that makes you think about functions, then that’s the right choice. We will be creating a new function along with totally random (new) color codes, and we will assign them to the colors array. Then we’ll fetch them in the color blocks/options array.
如果那让您考虑功能,那是正确的选择。 我们将创建一个带有完全随机(新)颜色代码的新函数,并将它们分配给colors数组。 然后,我们将它们放入颜色块/选项数组中。
Let’s see what the code looks like, and then we’ll go through it line by line.
让我们看一下代码的样子,然后逐行进行介绍。
A built-in method in JavaScript helps us generate a random number between 0 and 1. Then we make some manipulations to make sure that the range of that random number stays between the digits 0 and 255.
JavaScript中的内置方法可帮助我们生成介于0和1之间的随机数。然后,我们进行一些操作以确保该随机数的范围保持在数字0和255之间。
First we implement Math.random, selecting any random number between 0 and 1, then multiply the number by 256 since we don’t want the number to be any bigger than 255. Once we have a random number, we use Math.floor and make sure that we only have the digit before the decimal values (a whole number).
首先我们实现Math.random 选择0到1之间的任意随机数,然后将该数字乘以256,因为我们不希望该数字大于255。一旦我们有了一个随机数,就使用Math.floor并确保只有十进制值前的数字(整数)。
Lastly, we add up all of these numbers or variables to form a string. We return the string so it looks something like this: rgb(23, 45, 112).
最后,我们将所有这些数字或变量加起来形成一个字符串。 我们返回字符串,使其看起来像这样: rgb(23,45,112)。
But this will only return a string which looks like an RGB code. How will this be added to the array of colors we have? How will a random color be selected every time the game is started or reset?
但这只会返回看起来像RGB代码的字符串。 如何将其添加到我们拥有的颜色阵列中? 每次启动或重置游戏时如何选择随机颜色?
To accomplish both of these things, we’ll create a couple of more functions and see how they help us solve this issue.
为了完成这两项工作,我们将创建更多其他功能,并查看它们如何帮助我们解决此问题。
Select a random colour from the array
从阵列中选择随机颜色
To do this, we will create a new function called pickColor(). Let’s see how the function will look, and then we will break it down.
为此,我们将创建一个名为pickColor()的新函数。 让我们看看该函数的外观,然后将其分解。
function pickColor() { var random = Math.floor(Math.random() * colors.length); return colors[random];}
As simple as it can get, let’s see what these two powerful lines do for us.
尽可能简单,让我们看看这两条强大的代码对我们有什么作用。
As we have already seen with the magic of Math.random and Math.floor, we use the same function to get a random number generated between 0 and the length of the array.
正如我们已经用Math.random和Math.floor的魔力看到的那样,我们使用相同的函数来获取在0和数组长度之间生成的随机数。
Add six (or three) random RGB codes in the colors array
在颜色数组中添加六个(或三个)随机RGB代码
To do this, we use the above two functions, which are randomColors() and pickColors(). What the randomColors() function does in particular is that it runs the randomColors() function six or three times (depending on the mode of the game) and adds the corresponding number of RGB color codes to the colors array. We will name this generateRandomColor(num*) function. Let’s see how the code looks and break it down line by line.
为此,我们使用以上两个函数,它们是randomColors()和pickColors() 。 randomColors()函数的具体作用是,它会运行randomColors()函数六到三次(取决于游戏的模式),并将相应数量的RGB颜色代码添加到colors数组中。 我们将其命名为generateRandomColor(num *)函数。 让我们看看代码的外观并将其逐行分解。
*num will be decided on the basis of the mode of the game.
* num将根据游戏模式决定。
Now after all these new functions and all this code manipulation, our code base for app.js has changed quite a bit. Let’s see what it looks like now:
现在,在完成所有这些新功能以及所有这些代码操作之后,我们用于app.js的代码库已经发生了很大变化。 让我们看看现在是什么样子:
After almost setting up the primary logic, this may look like a cake walk. It’s all about creating a function and letting that function do its job against any given user input (in this case, a click of the reset button).
在基本设置了基本逻辑之后,这看起来像是步履蹒跚。 这一切都是关于创建一个函数并让该函数根据任何给定的用户输入(在这种情况下,单击“ 重置”按钮)来执行其工作。
All we want with the reset button is
我们想要的重置按钮是
Let’s see how the pseudo code would look:
让我们看一下伪代码的样子:
function reset() { //create a new array of 6 random colors //pick new random color //fill the squares with new set of generated colors}
I strongly recommend writing pseudo code while solving complex problems. This habit of writing pseudo code has helped me save a lot of time whenever I’m stuck on complex algorithmic challenges.
我强烈建议在解决复杂问题时编写伪代码。 每当我遇到复杂的算法挑战时,编写伪代码的习惯就帮助我节省了很多时间。
Alright, coming back to our reset button: let’s see how the actual function would look:
好了,回到我们的重置按钮:让我们看看实际功能如何:
Let’s break it down line by line:
让我们逐行将其分解:
This is what the updated app.js looks like after all the edits we have made:
在完成所有编辑后,更新后的app.js如下所示:
This looks pretty good for now! I am not adding the functionality for setting up the mode in this article, as it is already getting to big and I don’t want to bore you all :). But if you liked all of this, I will be more than happy to write another article covering the rest.
现在看起来不错! 我没有在本文中添加用于设置模式的功能,因为它已经变得越来越大了,我不想让所有人都感到厌烦:)。 但是,如果您喜欢所有这些,那么我将很乐意写另一篇文章,介绍其余内容。
Here’s the link for the GitHub repository where the final optimized code can be found.
这是GitHub存储库的链接 ,可以在其中找到最终的优化代码。
I hope this article inspires a few of you to learn more about DOM manipulation and this beautiful language of JavaScript. Until the next time!
我希望本文能激发一些人学习更多有关DOM操作和这种漂亮JavaScript语言的知识。 直到下一次!