javascript

基本类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Numbers
4
9.3
-10

//Strings
"Hello World"
"43"

//Booleans
true
false

//null and undefined
null
undefined

typeof 查看变量的数据类型。

使用格式:

typeof 变量名

number基本运算:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Numbers
4
9.3
-10

//We can do some math

4 + 10 //14
1/5 //0.2

//Modulo - remainder operator

10 % 3 //1
24 % 2 //0
15 % 11 //4

字符串基本运算:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Single or Double quotes OK
"hello world"
'hello world'

//Concatenation
"charlie" + "brown" //"charliebrown"

//Escape Characters start with "\"
"Singin \"Do wah diddy, diddy, dum diddy do\" "
"This is a backslash: \\"

//Strings have a length property
"hello world".length //11

//Access individual characters using [] and an index
"hello"[0] //"h"
"hello"[4] //"o"

变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
变量
格式:var 变量名 = 数据;

声明变量要注意的事项:
1.在javascript中声明变量是 使用var关键字声明的,javascript中的变量可以存储任意的数据类型数据.
2.javascript中变量数据类型是根据存储的值决定的,可以随时更改存储数据的类型。
3.定义了多个同名的变量是,后定义的同名变量是覆盖前面定义的同名变量。
4.声明变量的时候可以省略var关键字,但是不建议省略。

//Variables are simply containers that store values
//They follow this pattern:
var yourVariableName = yourValue;

//They can store all of the values we've seen
var name = "Rusty";
var secretNumber = 73;
var isAdorable = true;

//Recall the stored value by calling the variable name
var name = "Rusty";
"hello there " + name //"hello there Rusty"

var num = 37;
num + 3 + 10 //50

//We can also update existing variables
var name = "Robert";
name = "Bob";

null & undefined

1
2
3
4
5
6
7
8
9
10
11
//The two other primitives are null and undefined

//Variables that are declared but not
//initialized are undefined
//The following variables are undefined:
var name;
var age;

//null is "explicitly nothing"
var currentPlayer = "charlie";
currentPlayer = null; //game over

常用输出语句

1
2
3
4
alert() //弹出警告框
console.log() //只在控制台输出
prompt //弹出输入框
案例见下

js代码分离

index.html:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<title>Script Demo</title>

</head>
<body>
<h1>Including JS Files</h1>
<script src="script.js"></script>
</body>
</html>

script.js:

1
2
3
var userName = prompt("What is your name?");
alert("Nice to meet you, " + userName);
console.log("Also great to meet you, " + userName);

布尔逻辑

Operator Name Example ​Result
> Greater than x > 10 FALSE
>= Greater than or equal to x >= 5 TRUE
< Less than x < -50 FALSE
<= Less than or equal to x <= 100 TRUE
== Equal to x == “5” TRUE
!= Not equal to x != “b” TRUE
=== Equal value and type x === “5” FALSE
!== Not equal value or equal type x !== “5” TRUE

双等号与三等号比较特殊,双等号会转换类型让两者匹配再比较大小,而三个等号会比较类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var x = 99;

x == "99" //true

x === "99" //false


var y = null;

y == undefined //true

y === undefined //false


true == "1" //true

0 == false //true

null == undefined //true

NaN == NaN //false
Operator Name Example ​Result
&& AND x < 10 && x !== 5 false
|| OR y > 9 || x === 5 true
! NOT !(x === y) true

练习1:

1
2
3
4
var x = 10;
var y = "a"

y === "b" || x >= 10

练习2:

1
2
3
4
var x = 3;
var y = 8;

!(x == "3" || x === y) && !(y != 8 && x <= y)

练习3:

1
2
3
4
5
6
7
8
9
10
11
!"Hello World"

!""

!null

!0

!-1

!NaN

if

if 判断语句的语法:

if (condition) statement1 else if statement2 else statement3

如果条件计算结果为 true,则执行 statement1;如果条件计算结果为 false,则执行 statement2。
注意判断的条件会发生自动类型转换:
number:如果非0为true,0为false
string:如果非null或非空为true,否则为false
undefined:false
NaN: false
对象类型:非null为true,否则为false。

案例猜数字游戏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
<script type="text/javascript">
//create secretNumber
var secretNumber = 4;

//ask user for guess
var stringGuess = prompt("Guess a number");
var guess = Number(stringGuess);

//check if guess is right
if(guess === secretNumber) {
alert("YOU GOT IT RIGHT!");
}
//check if guess is higher
else if(guess > secretNumber){
alert("Too high. Guess again!");
}

else {
alert("Too low. Guess again!");
}
//otherwise, check if lower
</script>
</head>
<body>

</body>
</html>

case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
case选择语句:
switch语句

switch(变量){
case1:

break;
case2

break;
case3:

break;

.....

default

break;

}

特殊之处:
在javascript中case后面可以跟常量与变量还可以跟表达式。
案例一:
function test6() {
var color = "xx";
var value1 = "red", value2 = "green";
switch(color) {
case value1:
alert("红色");
break;
case value2:
alert("绿色");
break;
default:
alert("执行默认default");
}
}
这里,switch 语句用于字符串 Color,声明 case 使用的是变量 BLUE、RED 和 GREEN,这在 ECMAScript 中是完全有效的。

案例二:
var num = 20;
switch(true) {
case num >= 0 && num <= 10:
alert("大于0小于等于10");
break;
case num>10 && num<=20:
alert("大于10小于等于20");
break;
}

循环语句

while

while循环语句:

	格式:
		while(判断的条件){
			循环体内容
		}

while(count<5){
document.write(“hello world
”);
count++;
}

do-while循环语句

do{
	循环语句;
}while(判断条件);

需求;计算1~100奇数的总和。

var num = 1;
var result = 0;
do{
	if(num%2!=0){
		result +=num;
	}
	num++;
}while(num<=100);

document.write("结果:"+result);

for循环语句:

格式:
	for(初始化语句; 判断的条件 ; 循环后的语句){
		循环体语句;
	}

需求;计算1~100偶数的总和。
var result = 0 ;
for(var i = 1 ; i<=100 ; i++){
if(i%2==0){
result +=i;
}
}
document.write(“结果:”+result);

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
console.log("PRINTING ALL NUMBERS BETWEEN -10 AND 19");

for(var i = -10; i < 20; i++){
console.log(i)
}



console.log("PRINTING ALL EVEN BETWEEN 10 AND 40");

// for(var i = 11; i <= 40; i += 2){
// console.log(i);
// }

for(var i = 10; i <= 40; i += 1){
if(i % 2 === 0) {
console.log(i);
}
}




console.log("PRINTING ALL ODD NUMBERS BETWEEN 300 AND 333");

for(var i = 300; i <= 333; i++) {
if(i % 2 !== 0) {
console.log(i);
}
}

console.log("PRINTING ALL NUMBERS DIVISIBLE BY 5 AND 3 BETWEEN 5 AND 50");

for(var i = 5; i <= 50; i++){
if(i % 5 === 0 && i % 3 === 0) {
console.log(i);
}
}

函数function

函数的定义格式:

function 函数名(形参列表){
	函数体 ;
}

javascript的函数要注意的细节:
1. 在 javascript中函数 定义形参时是不能使用var关键字声明变量 的。
2. 在javascript中 的函数是没有返回值类型 的,如果函数需要返回数据给调用者,直接return返回即可,如果不需要返回则不返回。
3. 在 javascript中是没有函数 重载 的概念 的,后定义的同名函数会直接覆盖前面定义同名函数。
4. 在javascript中任何的函数内部都隐式的维护了一个arguments(数组)的对象,给函数 传递数据的时候,是会先传递到arguments对象中,
然后再由arguments对象分配数据给形参的。
5.函数本身就是一个对象,此对象的名字就是函数名
需求:定义一个函数做两个参数的加法功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
function  add(a,b){
var sum = a+b;
return sum;
}

function add(){

for(var index = 0 ; index<arguments.length ; index++){
console.log(arguments[index]+",");
}
}
//调用函数
add(11,21,13,14);

函数本身就是一个对象,此对象的名字就是函数名

1
2
3
4
5
function show (a) {
// body...
}
var p = show;
alert(p);//此语句将会把函数的所有内容都打印出来

动态函数
动态函数的特点时new一个Function对象,往对象中可以传入变量,函数体,以及输出语句。

1
2
3
var show = new Function("x","y","var sum = x + y;return sum;");
var p = show(1,5);
alert(p);

匿名函数,通常在定义事件属性的行为时较为常用。

1
2
var show = function(){alert("哈哈")};//此为常见了一个匿名函数,并为其取了一个名字show。
show();

数组

初始化数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var friends = ["Charlie", "Liz", "David", "Mattias"];

//初始化一个空的数组
var friends = []; //no friends :(
var friends = new Array() //uncommon

//Arrays can hold any type of data
var random_collection = [49, true, "Hermione", null];




Arrays let us group data together in lists
Array are indexed starting at 0. Every slot has a corresponding number
We can use those indices to retrieve data
var friends = ["Charlie", "Liz", "David", "Mattias"];

console.log(friends[0]) //"Charlie"

friends[1] + " <3 " + friends[2] //"Liz <3 David"

Arrays have a length property:
var nums = [45,37,89,24];
nums.length //4

更新数组:

1
2
3
4
5
6
7
var friends = ["Charlie", "Liz", "David", "Mattias"];

friends[0] = "Chuck";
friends[1] = "Lizzie";
//增加新元素
var friends = ["Charlie", "Liz", "David", "Mattias"];
friends[4] = "Amelie";

数组方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var colors = ["red", "orange", "yellow"];
colors.push("green");
//["red", "orange", "yellow", "green"]

var colors = ["red", "orange", "yellow"];
colors.pop();
//["red", "orange"]

//pop() returns the removed element
var col = colors.pop(); //orange

var colors = ["red", "orange", "yellow"];
colors.unshift("infrared")
//["infrared", "red", "orange", "yellow"]

var colors = ["red", "orange", "yellow"];
colors.shift();
//["orange", "yellow"]

//shift() also returns the removed element
var col = colors.shift(); //orange

var friends = ["Charlie", "Liz", "David", "Mattias", "Liz"];

//returns the first index at which a given element can be found
friends.indexOf("David"); //2
friends.indexOf("Liz"); //1, not 4

//returns -1 if the element is not present.
friends.indexOf("Hagrid"); //-1

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
//use slice to copy the 2nd and 3d fruits
//specify index where the new array starts(1) and ends(3)
var citrus = fruits.slice(1, 3);

//this does not alter the original fruits array
//citrus contains ['Orange','Lemon']
//fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];

//you can also use slice() to copy an entire array
var nums = [1,2,3];
var otherNums = nums.slice();
//both arrays are [1,2,3]

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
//use splice to remove 'Orange' from the array
//specify index of the element to be removed and
//how many elements should be removed from that index
fruits.splice(1, 1);
// returns: ["Orange"]
console.log(fruits);
// prints: ["Banana", "Lemon", "Apple", "Mango"]

数组循环:

1
2
3
4
5
6
7
8
9
10
11
12
13
//with a for loop
var colors = ["red", "orange", "yellow", "green"];

for(var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}

//using forEach
var colors = ["red", "orange","yellow", "green"];

colors.forEach(function(color){
console.log(color);
});

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html>
<head>
<title>Todo List</title>
<script type="text/javascript">
var todos = ["Buy New Turtle"];

var input = prompt("What would you like to do?");

while(input !== "quit"){
//handle input
if(input === "list") {
printList();
} else if(input === "new") {
addTodo();
} else if(input === "delete") {
deleteTodo();
}
//ask again for new input
input = prompt("What would you like to do?");
}
console.log("OK, YOU QUIT THE APP");

function printList() {
console.log("**********");
todos.forEach(function(todo, index){
console.log(index + ": " + todo);
});
console.log("**********");
}

function addTodo(){
//ask for new todo
var newTodo = prompt("Enter new todo");
//add to todos array
todos.push(newTodo);
console.log(newTodo + " added to list")
}

function deleteTodo(){
var index = prompt("Enter index of todo to delete");
todos.splice(index, 1);
console.log("Todo Removed")
}
</script>
</head>
<body>
<h1>Todo List</h1>

<ul>
<li>"new" - Add A Todo</li>
<li>"list" - List All Todos</li>
<li>"delete" - Remove Specific Todo</li>
<li>"quit" - Quit App</li>
</ul>

</body>
</html>

案例2:构建自己的foreach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// =========
// VERSION 1
// =========
function myForEach(arr, func){
for (var i = 0; i < arr.length; i++) {
func(arr[i]);
}
}

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
myForEach(colors, function(color){
console.log(color);
});

// =========
// VERSION 2
// =========
Array.prototype.myForEach = function(func){
for(var i = 0; i < this.length; i++) {
func(this[i]);
}
};

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
colors.myForEach(function(color){
console.log(color);
});

对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

var person = {
name: "Travis",
age: 21,
city: "LA"
};
//bracket notation, similar to arrays:
console.log(person["name"]);
//dot notation:
console.log(person.name);

There are a few differences between the 2 notations:

//you cannot use dot notation if the property starts with a number
someObject.1blah //INVALID
someObject["1blah"] //VALID!
//you can lookup using a variable with bracket notation
var str = "name";
someObject.str //doesn't look for "name"
someObject[str] //does evaluate str and looks for "name"
//you cannot use dot notation for property names with spaces
someObject.fav color //INVALID
someObject["fav color"]; //VALID

对象更新

1
2
3
4
5
6
7
8
9
var person = {
name: "Travis",
age: 21,
city: "LA"
};
//to update age
person["age"] += 1;
//to update city
person.city = "London";

创建对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//make an empty object and then add to it
var person = {}
person.name = "Travis";
person.age = 21;
person.city = "LA";
//all at once
var person = {
name: "Travis",
age: 21,
city: "LA"
};
//another way of initializing an Object
var person = new Object();
person.name = "Travis";
person.age = 21;
person.city = "LA";

对象中可以容纳任何数据

var junkObject = {
age: 57,
color: “purple”,
isHungry: true,
friends: [“Horatio”, “Hamlet”],
pet: {
name: “Rusty”,
species: “Dog”,
age: 2
}
};
对象中可以容纳方法
junkObject.add = function(a,b){
return a+b;
}

使用this,使用对象中的已有元素

junkObject.print = function(){
this.friends.forEach(function(arr){console.log(arr);});
}

DOM

The Document Object Model is the interface between your Javascript and HTML+CSS
在控制台输入:document 以及 console.dir(document)即会显示出js文档对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
As you begin working with the DOM you'll be writing some JavaScript code that selects HTML elements from the page and manipulates them.

When doing this, be sure to include your JavaScript code at the bottom of the HTML document, right before the closing </body> tag.

The HTML will need to have loaded before the JavaScript is run, otherwise the JavaScript will throw an error because the HTML that it is trying to select and manipulate doesn't exist (yet).

See example below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h1>Some HTML Code Here</h1>

<script src="scriptfile.js"></script>
</body>
</html>

dom 5类选择器

document.getElementById()
document.getElementsByClassName()
document.getElementsByTagName()
document.querySelector()
document.querySelectorAll()

Hello

Goodbye

  • List Item 1
  • List Item 2
  • List Item 3

var tag = document.getElementById(“highlight”);
var tags = document.getElementsByClassName(“bolded”);
var tags = document.getElementsByTagName(“li”);
//select by ID 所有都可选择
var tag = document.querySelector("#highlight");
//select by Class
var tag = document.querySelector(".bolded");
//select by tag
var tag = document.querySelector(“h1”);

//select by tag
var tags = document.querySelectorAll(“h1”);
//select by class
var tags = document.querySelectorAll(".bolded");

交互dom

changing an element’s style

1
2
3
4
5
6
7
8
9
/SELECT
var tag = document.getElementById("highlight");

//MANIPULATE
tag.style.color = "blue";
tag.style.border = "10px solid red";
tag.style.fontSize = "70px";
tag.style.background = "yellow";
tag.style.marginTop = "200px";

adding/removing classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*DEFINE A CLASS IN CSS*/
.another-class {
color: purple;
fontSize: 76px;
}

var tag = document.querySelector("h1");

//ADD A CLASS TO THE SELECTED ELEMENT
tag.classList.add("another-class");

//REMOVE A CLASS
tag.classList.remove("another-class");

//TOGGLE A CLASS 改变 如果有这个class就会变为没有,如果没有这个class就会添加。
tag.classList.toggle("another-class");

changing the content of a tag

1
2
3
4
5
6
7
8
9
10
11
<p>
This is an <strong>awesome</strong> paragraph
</p>
/Select the <p> tag:
var tag = document.querySelector("p");

//Retrieve the textContent:
tag.textContent //"This is an awesome paragraph"

//alter the textContent:
tag.textContent = "blah blah blah";
1
2
3
4
5
6
7
8
9
<p>
This is an <strong>awesome</strong> paragraph
</p>

//Select the <p> tag:
var tag = document.querySelector("p");

tag.innerHTML
//"This is an <strong>awesome</strong> paragraph"

changing attributes(src, href, etc.)

1
2
3
4
5
6
7
8
9
10
11
12
13
<a href="www.google.com">I am a link</a>
<img src="logo.png">

var link = document.querySelector("a");
link.getAttribute("href"); //"www.google.com"
//CHANGE HREF ATTRIBUTE
link.setAttribute("href","www.dogs.com");
///<a href="www.dogs.com">I am a link</a>

//TO CHANGE THE IMAGE SRC
var img = document.querySelector("img");
img.setAttribute("src", "corgi.png");
//<img src="corgi.png">

DOM Events

1
2
3
4
5
6
7
8
9
10
11
12
Clicking on a button
Hovering over a link
Dragging and Dropping
Pressing the Enter key

To add a listener, we use a method called addEventListener
element.addEventListener(type, functionToCall);

var button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("SOMEONE CLICKED THE BUTTON!");
});
1
2
3
4
5
6
7
8
9
10
<button>Click Me</button>
<p>No One Has Clicked Me Yet</p>

var button = document.querySelector("button");
var paragraph = document.querySelector("p");

//SETUP CLICK LISTENER
button.addEventListener("click", function() {
paragraph.textContent = "Someone Clicked the Button!";
});

案例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<title>Color Toggle</title>

<style type="text/css">
.purple {
background: purple;
}
</style>
<script type="text/javascript">
var button = document.querySelector("button");
// var isPurple = false;


// button.addEventListener("click", function(){
// if(isPurple){
// document.body.style.background = "white";
// } else {
// document.body.style.background = "purple";
// }
// isPurple = !isPurple;
// });
button.addEventListener("click", function(){
document.body.classList.toggle("purple");
});
</script>
</head>
<body>
<button>CLICK ME</button>


<script type="text/javascript" src="toggle.js"></script>
</body>
</html>

综合案例:猜颜色

第一步:布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!DOCTYPE html>
<html>
<head>
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="colorGame.css">
<style type="text/css">
body {
background-color: #232323;
}

.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}

#container {
margin: 0px auto;
max-width: 600px;
}

h1 {
color: white;
}

</style>
<script type="text/javascript">

var colors = [
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)"
];

var squares = document.querySelectorAll(".square");
var pickedColor = colors[3];
var colorDisplay = document.getElementById("colorDisplay");

colorDisplay.textContent = pickedColor;

for(var i = 0; i < squares.length; i++){
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];

//add click listeners to squares
squares[i].addEventListener("click", function() {
//grab color of clicked squares
var clickedColor = this.style.backgroundColor;
//compare color to pickedColor
if(clickedColor === pickedColor) {
alert("Correct!");
} else {
alert("WRONG!!!");
}
});
}
</script>
</head>



<body>
<h1>
The Great <span id="colorDisplay">RGB</span> Color Game
</h1>

<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="colorGame.js"></script>
</body>
</html>

第2步:点击事件

正确时显示同一颜色,不正确时为黑色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html>
<head>
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="colorGame.css">
<style type="text/css">
body {
background-color: #232323;
}

.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}

#container {
margin: 0px auto;
max-width: 600px;
}

h1 {
color: white;
}

/*提示颜色白色*/
span {
color: white;
}

</style>
</head>



<body>
<h1>
The Great <span id="colorDisplay">RGB</span> Color Game
</h1>
<!-- 提示 -->
<div>
<span id="message"></span>
</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">


var colors = [
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)"
];
// 正确后所有都为同一颜色
function changeColors(color) {
//loop through all squares
for(var i = 0; i < squares.length; i++) {
//change each color to match given color
squares[i].style.backgroundColor = color;
}
}
// 目标颜色随机
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");

colorDisplay.textContent = pickedColor;

for(var i = 0; i < squares.length; i++){
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];

//add click listeners to squares
squares[i].addEventListener("click", function() {
//grab color of clicked squares
var clickedColor = this.style.backgroundColor;
//compare color to pickedColor
if(clickedColor === pickedColor) {
messageDisplay.textContent = "Correct!";
// 正确后所有都为同一颜色
changeColors(clickedColor);
} else {
// 不正确颜色为黑色
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Try Again";
}
});
}
</script>
</body>

</html>

第3步:随机颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<!DOCTYPE html>
<html>
<head>
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="colorGame.css">
<style type="text/css">
body {
background-color: #232323;
}

.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}

#container {
margin: 0px auto;
max-width: 600px;
}

h1 {
color: white;
}

/*提示颜色白色*/
span {
color: white;
}

</style>
</head>



<body>
<h1>
The Great <span id="colorDisplay">RGB</span> Color Game
</h1>
<!-- 提示 -->
<div>
<span id="message"></span>
</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">


// 随机颜色
var colors = generateRandomColors(6);
// 正确后所有都为同一颜色
function changeColors(color) {
//loop through all squares
for(var i = 0; i < squares.length; i++) {
//change each color to match given color
squares[i].style.backgroundColor = color;
}
}
// 目标颜色随机
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}


function generateRandomColors(num) {
//make an array
var arr = [];
//add num random colors to arr
for(var i = 0; i < num; i++) {
//get random color and push into arr
arr.push(randomColor());
}
//return that array
return arr;
}

function randomColor() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//pick a "green" from 0 - 255
var g = Math.floor(Math.random() * 256);
//pick a "blue" from 0 - 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
// 获取h1标签
var h1 = document.querySelector("h1");
colorDisplay.textContent = pickedColor;

for(var i = 0; i < squares.length; i++){
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];

//add click listeners to squares
squares[i].addEventListener("click", function() {
//grab color of clicked squares
var clickedColor = this.style.backgroundColor;
//compare color to pickedColor
if(clickedColor === pickedColor) {
messageDisplay.textContent = "Correct!";
// 正确后所有都为同一颜色
changeColors(clickedColor);
// 将h1标签颜色变为指定颜色
h1.style.background = clickedColor;
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Try Again";
}
});
}


</script>
</body>

</html>

第4步:布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<!DOCTYPE html>
<html>
<head>
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="colorGame.css">
<style type="text/css">

body {
background-color: #232323;
margin: 0;
}

.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
border-radius: 15%;
transation:background 0.6s;
-webkit-transation:background 0.6s;
-moz-transation:background 0.6s;
}

#container {
margin: 0px auto;
max-width: 600px;
}

h1 {
text-align: center;
color: white;
background: steelblue;
margin:0;
text-transform: uppercase;
font-weight: normal;
padding: 20px 0;
}

/*提示颜色白色*/
span {
color: black;
}

#stripe {
background: white;
height: 30px;
text-align: center;
color: black;
}

.selected {
background: blue;
}

button{

border: none;
background: none;
text-transform: uppercase;
height: 100%;
font-weight: 700;
color: steelblue;
letter-spacing: 1px;
}
/*中间的*/
#message{
display: inline-block;
width: 10%;
}

button:hover{
color: white;
background: steelblue;
transition: all 0.3s;
}
</style>
</head>



<body>
<h1>
The Great <span id="colorDisplay">RGB</span> Color Game
</h1>
<!-- 信息横条-->
<div id="stripe">
<button id="reset">New Colors</button>
<span id="message"></span>
<button id="easyBtn">Easy</button>
<button id="hardBtn" class="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">


// 随机颜色
var colors = generateRandomColors(6);

var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
// 获取h1标签
var h1 = document.querySelector("h1");
colorDisplay.textContent = pickedColor;




// 点击按钮更换下一批颜色
var resetButton = document.querySelector("#reset");

var numSquares = 6;


var easyBtn = document.querySelector("#easyBtn");
var hardBtn = document.querySelector("#hardBtn");

easyBtn.addEventListener("click", function() {
easyBtn.classList.add("selected");
hardBtn.classList.remove("selected");
numSquares = 3;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
if(colors[i]) {
squares[i].style.background = colors[i];
} else {
squares[i].style.display = "none";
}
}
});

hardBtn.addEventListener("click", function() {
hardBtn.classList.add("selected");
easyBtn.classList.remove("selected");
numSquares = 6;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
squares[i].style.background = colors[i];
squares[i].style.display = "block";
}
});

resetButton.addEventListener("click", function() {

colors = generateRandomColors(numSquares);
//pick a new random color from array
pickedColor = pickColor();
//change colorDisplay to match picked Color
colorDisplay.textContent = pickedColor;
//change colors of squares
for(var i = 0; i < squares.length; i++) {
squares[i].style.background = colors[i];
}
h1.style.background = "#232323";
});



// 正确后所有都为同一颜色
function changeColors(color) {
//loop through all squares
for(var i = 0; i < squares.length; i++) {
//change each color to match given color
squares[i].style.backgroundColor = color;
}
}
// 目标颜色随机
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}


function generateRandomColors(num) {
//make an array
var arr = [];
//add num random colors to arr
for(var i = 0; i < num; i++) {
//get random color and push into arr
arr.push(randomColor());
}
//return that array
return arr;
}

function randomColor() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//pick a "green" from 0 - 255
var g = Math.floor(Math.random() * 256);
//pick a "blue" from 0 - 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}


for(var i = 0; i < squares.length; i++){
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];

//add click listeners to squares
squares[i].addEventListener("click", function() {
//grab color of clicked squares
var clickedColor = this.style.backgroundColor;
//compare color to pickedColor
if(clickedColor === pickedColor) {
messageDisplay.textContent = "Correct!";

resetButton.textContent = "Play Again?";
// 正确后所有都为同一颜色
changeColors(clickedColor);
// 将h1标签颜色变为指定颜色
h1.style.background = clickedColor;
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Try Again";
}
});
}


</script>
</body>

</html>