JavaScript's dom and events

 

 

Animation

Now that we know how to select and change DOM elements, we can create a simple animation.

Let's create a simple HTML page that contains box elements that will use JS animation.

<style>
#container {
  width: 400px;
  height: 400px;
  background: green;
  position: relative;
}
#box {
  width: 30px;
  height: 30px;
  background: red;
  position: absolute;
}
</style>
<div id="container">
   <div id="box"> </div>
</div>

try it

Our box element is inside the container element. Note the position attribute used for the element:

The container is relative, the box is absolute. This will allow us to create animations relative to the container.

We will animate the red box to move it to the right side of the container.

Tip: You need to be familiar with CSS to better understand the provided code.

 

Animation

To create an animation, we need to change the properties of the element in small intervals.

We can  achieve this by using the  setInterval() method, which allows us to create a timer and call a function that repeatedly changes properties at a defined interval (in milliseconds).

E.g:

var t = setInterval(move, 500); 

This code creates a  timer that calls the move() function every 500 milliseconds  .

Now we need to define the  move()  function to change the position of the box.

// 定义开始的位置
var pos = 0; 
// 获取box元素
var box = document.getElementById("box");

function move() {
  pos += 1;
  box.style.left = pos+"px"; //px = pixels
}

Tip: The move() function increases the left attribute of the box element by 1 each time it is called.

 

HTML DOM

Through  HTML DOM , JavaScript can access all elements of HTML documents.

HTML DOM (Document Object Model)

When the web page is loaded, the browser creates the Document Object Model of the page.

The HTML DOM model is structured as a tree of objects:

Through the programmable object model, JavaScript has gained enough power to create dynamic HTML.

  • JavaScript can change all HTML elements in the page
  • JavaScript can change all HTML attributes in the page
  • JavaScript can change all CSS styles in the page
  • JavaScript can react to all events in the page

DOM Tree

DOM means that the document is a tree structure.

HTML elements become related nodes in the tree.

There is a certain relationship between all nodes in the tree.

A node can have child nodes. Nodes that have the same parent node are called sibling nodes.

For example, consider the following structure:

<html> has two child nodes (<head>, <body>);

<head> has a child node (<title>) and a parent node (<html>);

<title> has a parent node (<head>) and no child nodes;

<body> has two child nodes (<h1> and <a>) and a parent node (<html>);

Tip: It is important to understand the relationship between elements in an HTML document so that you can use JavaScript to manipulate them.

document object

documentThe object is the root node of the document, and the window.documentattributes point to this object. In other words, as long as the browser starts to load the HTMLdocument, this object begins to exist and can be called directly.

There is a predefined document object in JavaScript that can be used to access all elements on the DOM.

In other words, the document object is the owner (or root) of all objects in the web page.

Therefore, if you want to access an object in an HTML page, always access the  document  object.

E.g:

document.body.innerHTML = "Some text";

Since the body is an element of the DOM, we can use the document object to access it and change the content of the innerHTML property.

Select element

All HTML elements are objects. And we know that every object has properties and methods.

The document  object has three methods most commonly used to select HTML elements:

//通过 id 找元素
document.getElementById(id) 

//通过 类 找元素
document.getElementsByClassName(name) 

//通过 标签 找元素
document.getElementsByTagName(name)

as the picture shows:

 

In the following example, the getElementById  method is used to select the element with id="demo" and change its content:

var elem = document.getElementById("demo");
elem.innerHTML = "Hello World";

 

Select element

The getElementsByClassName()  method finds all elements by class name and returns them as an array.

For example, if our HTML page contains three elements with  class="demo" , the following code will return all these elements as an array:

<div class="demo">
    <span class="demo">Hi I'm Loen!</span>
</div>
<p class="demo">This is a paragraph</p>
<script>
var arr =  document.getElementsByClassName("demo");
//访问第二个元素
arr[1].innerHTML = "Hi I am Peter";
</script>

try it

Similarly, the getElementsByTagName  method returns all the elements of the specified tag name as an array.

The following example gets all the paragraph elements of the page and changes their content:

<p>hi</p>
<p>hello</p>
<p>hi</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
  arr[x].innerHTML = "Hi there";
}
</script>

try it

The script changes the HTML to:

<p>Hi there</p>
<p>Hi there</p>
<p>Hi there</p>

Tip: We usually use the length property of the array to loop through all the selected elements in the above example.

Use DOM

Each element in the DOM has a set of attributes and methods, which provide information about their relationship in the DOM:

element.childNodes  returns an array of child nodes of an element.

element.firstChild  returns the first child node of the element.

element.lastChild  returns the last child node of the element.

element.hasChildNodes  returns true if the element has any child nodes, otherwise it is false.

element.nextSibling  returns the next node at the same tree level.

element.previousSibling  returns the previous node at the same tree level.

element.parentNode  returns the parent node of the element.

For example, we can select all child nodes of an element and change its content:

<html>
  <body>
    <div id ="demo">
      <p>一些文本</p>
      <p>另一些文本 </p>
    </div>

    <script>
     var a = document.getElementById("demo");
     var arr = a.childNodes;
     for(var x=0;x<arr.length;x++) {
       arr[x].innerHTML = "新的文本";
     }
    </script>

  </body>
</html>

try it

Change attributes

After selecting the element you want to use, you can change its attributes.

As we saw in the previous lessons, we can use the  innerHTML  attribute to change the text content of an element.

Similarly, we can change the attributes of elements.

For example, we can change the src  attribute of the image  :

<img id="myimg" src="https://www.w3cschool.cn/attachments/cover/cover_php.jpg" alt="" />
<script>
var el = document.getElementById("myimg"); // 通过id="myimg"获取元素
el.src = "https://www.w3cschool.cn/attachments/cover/cover_html.png";
</script>

try it

We can change the href attribute of the link:

<a href="http://www.baidu.com">百度</a>
<script>
var el = document.getElementsByTagName("a");
el[0].href = "https://www.w3cschool.cn";
el[0].innerHTML = "W3Cschool";
</script>

try it

Tip: In fact, you can use JavaScript to change all the attributes of an element.

Change style

The style of HTML elements can also be changed using JavaScript.

You can use the style  object of the element  to access all style attributes.

E.g:

<div id="demo" style="width:200px">一些文本</div>
<script>
  var x = document.getElementById("demo");
  x.style.color = "6600FF";
  x.style.width = "100px";
</script>

try it

The above code changes the text color and width of the div element.

Tip: All CSS properties can be set and modified using JavaScript. Remember, you cannot use dashes (-) in the property name: these are replaced with camel case, where the compound word starts with a capital letter. For example: the background-color property should be written as  backgroundColor .

Add and remove elements

Use the following method to create a new node:

element.cloneNode()  clones the element and returns the result node.

document.createElement(element)  creates a new element node.

document.createTextNode(text)  creates a new text node.

E.g:

var node = document.createTextNode("一些新的文本");

This will create a new text node, but it will not appear in the document until you attach it to an existing element using one of the following methods:

element.appendChild(newNode)  adds a new child node to the element as the last child node.

element.insertBefore(node1, node2)  insert node1 as a child node before node 2.

E.g:

<div id ="demo">一些文本</div>

<script>
  //创建一个新的段落
  var p = document.createElement("p");
  var node = document.createTextNode("一些新的文本");
  //添加文本到段落
  p.appendChild(node);

  var div = document.getElementById("demo");
  //将段落添加到div中
  div.appendChild(p);
</script>

 

Remove element

To delete an HTML element, you must select the element's parent and use the  removeChild(node)  method.

E.g:

<div id="demo">
  <p id="p1">这是一个段落.</p>
  <p id="p2">这是另外一个段落.</p>
</div>

<script>
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>

try it

This will delete the paragraph with id="p1" from the page.

Tip: Another way to achieve the same result is to use the  parentNode  property to get the parent of the element to be deleted:

var child = document.getElementById("p1");
child.parentNode.removeChild(child);

Replacement element

To replace HTML elements, use the  element.replaceChild(newNode,oldNode)  method.

E.g:

<div id="demo">
  <p id="p1">这是一个段落</p>
  <p id="p2">这是另一个段落</p>
</div>

<script>
var p = document.createElement("p");
var node = document.createTextNode("这是新的文本");
p.appendChild(node);

var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.replaceChild(p, child);
</script>

try it

Tip: The above code creates a new paragraph element that replaces the existing p1 paragraph.

javascript event

 

Events

 

event

JavaScript enables us to create dynamic pages. Every element in a web page can generate certain events that trigger JavaScript functions.

We can think of an event as a behavior that can be detected by JavaScript.

Event stream

The so-called event flow can also be understood as the trajectory of events. Generally, the event flow is divided into three stages: capture stage, target stage and bubbling stage.

Complete event stream

 

You can write Javascript code that is executed by events, such as when the user clicks on an HTML element, moves the mouse or submits a form.

When an event occurs on the target element, the processing function is executed.

Common HTML events include:

Tip: Corresponding events can be added to HTML elements as attributes.

E.g:

 

<p id="tip">这边显示提示</p>

<h2 id="tip">这边显示提示</h2>

<hr>

<p onclick="clickfn()">点击我看看</p>

<br>

<input type="text" onfocus="focusfn()" onblur="blurfn()"  value="获得焦点" />

<br><br>

<div onmouseover="moverfn()" onmouseout="moutfn()" style="">

    鼠标移动进来看看

</div>

Handling events

When the user clicks the designated button, we will display a reminder pop-up window:

<button onclick="show()">点击我</button>
<script>
function show() {
  alert("你好,我在这里!");
}
</script>

try it

You can bind event listeners to elements:

 

var x = document.getElementById("demo");

x.onclick = function () {

  document.getElementById("date").innerHTML = new Date();

}

try it

 

event

When the user enters or leaves the page, onload  and  onunload  events are triggered  . These operations are very useful when performing operations after the page loads.

<body onload="doSomething()">

Similarly, the window.onload  event can be used to run code after the entire page is loaded.

window.onload = function() {
   alert("整个页面已经加载完成");
}

try it

The onchange  event is mainly used for text boxes. When the text in the text box changes and the focus is lost from the element, the event handler is called.

E.g:

<input type="text" id="name" onchange="change()">
<script>
function change() {
 var x = document.getElementById("name");
 x.value= x.value.toUpperCase(); // 转成大写
}
</script>

try it

The above program will convert the value to uppercase when the user name changes.

Event monitoring

The addEventListener()  method attaches the event handler to the element without overwriting the existing event handler. You can add many event handlers to an element.

You can also add many event handlers of the same type to one element, that is, two "click" events.

element.addEventListener(event, function [, useCapture]);

The first parameter is the type of event (such as "click" or "mouseover").

The second parameter is the function to be called when the event occurs.

The third parameter is a Boolean value that specifies whether to use event bubbling or event capture. This parameter is optional and will be explained in the next lesson.

Tip: There is no on when adding event types, click instead of onclick

element.addEventListener("click", myFunction);
element.addEventListener("mouseover", myFunction);

function myFunction() {
  alert("Hello W3Cschool");
}

Delete event listener

We can use  removeEventListener to  delete event listeners:

element.removeEventListener("mouseover", myFunction);

We create an event handler, which will be automatically deleted after execution:

<button id="demo">开始</button>

<script>
var btn = document.getElementById("demo");
btn.addEventListener("click", myFunction);

function myFunction() {
  alert(Math.random());
  btn.removeEventListener("click", myFunction);
}
</script>

try it

After clicking the button, an alert with a random number will be displayed and the event listener will be deleted.

Tip: Internet Explorer version 8 and lower versions do not support the addEventListener() and removeEventListener() methods. However, you can use the document.attachEvent() method to attach event handlers in Internet Explorer.

Image slideshow

Now we can create a sample image slideshow project. The image will be changed using the "Next" and "Previous" buttons.

Now, let's create our HTML, which includes an image and two navigation buttons:

<div>
  <button> 上一个 </button>
  <img id="slider" src="https://www.w3cschool.cn/statics/images/logo.png" />
  <button> 下一个 </button>
</div>

try it

Next, let's define our example image in an array:

var images = [
   "https://www.w3cschool.cn/statics/images/1.png", 
   "https://www.w3cschool.cn/statics/images/2.png, 
   "https://www.w3cschool.cn/statics/images/3.png"
];

Tip: We will use three sample images that we uploaded to our server. You can use any number of images.

Image slideshow

Now we need to process the "Previous" and "Next" button clicks and call the corresponding functions to change the image.

HTML:

<div>
  <button onclick="prev()"> 上一个 </button>
  <img id="slider" src="https://www.w3cschool.cn/statics/images/1.png" />
  <button onclick="next()"> 下一个 </button>
</div>

JS:

var images = [
   "https://www.w3cschool.cn/statics/images/1.png", 
   "https://www.w3cschool.cn/statics/images/2.png, 
   "https://www.w3cschool.cn/statics/images/3.png"
];
var num = 0;

function next() {
  var slider = document.getElementById("slider");
  num++;
  if(num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
  }

function prev() {
  var slider = document.getElementById("slider");
  num--;
  if(num < 0) {
    num = images.length-1;
  }
  slider.src = images[num];
}

Tip: The num variable saves the current image. The next and previous button clicks are handled by their corresponding functions, which will change the source of the image to the next/previous image in the array.

sgt5

Form verification

HTML5 adds some attributes that allow form validation. For example, the require  attribute can be added to the input field to make it mandatory.

More complex form validation can be done using JavaScript.

The form element has an onsubmit  event that can be processed to perform validation  .

For example, we create a form with two input boxes and a button. The text in the two fields should be the same and cannot be empty to pass the verification.

<form onsubmit="return validate()" method="post">
  Number: <input type="text" name="num1" id="num1" />
  <br />
  Repeat: <input type="text" name="num2" id="num2" />
  <br />
  <input type="submit" value="Submit" />
</form>

Now we need to define the  validate()  function:

function validate() {
  var n1 = document.getElementById("num1");
  var n2 = document.getElementById("num2");
  if(n1.value != "" && n2.value != "") {
    if(n1.value == n2.value) {
      return true;
    }
  }
  alert("输入两个值不相等,请重新输入!");
  return false;
}

Only return true if the values ​​are not empty and equal.

Tip: If its onsubmit event returns false, the form will not be submitted.

Comprehensive use of slot game development


task

Now combine the knowledge points we learned before to complete a slot game.

1. First we generate 3 random numbers, ranging from 1 to 3.

Variable respectively  slotOne, slotTwo, slotThreeto the random number 3 is stored.

Tip: You may need to use Math.floor() and Math.random() methods.

2. Create an if statement, when  slotOne, slotTwo, slotThreethe values are equal, when the "Congratulations, you won!" Appended to the class as html logger in and return slotOne;.

3. Update the HTML on each slot machine to the corresponding number (the slot machine’s class is slot).

4. Set all slot machines to display corresponding pictures based on random numbers, and finally click run.

1. First, we generate 3 random numbers, ranging from 1 to 3. Respectively  slotOne, slotTwo, slotThreeto the random number 3 is stored.

Math.floor(Math.random() * (3 - 1 + 1)) + 1;

2、Now our slot machine generates 3 random numbers every time, we have to check whether the random numbers are all equal.

If all are equal, we should prompt the user that they won and return the winning number, otherwise we should return null.

When these 3 random numbers are equal, it is determined that the user wins. Create one if条件语句and use multiple conditions in order to check if they are equal. Similar to:

if (slotOne === slotTwo && slotTwo === slotThree){

  return slotOne;

} else {

}

When the three random numbers are the same, we  "It's A Win" append them to the class  loggerhtml.

3. $(".slot") Get all slot machines with jQuery selector  .

Once all the slot machines are obtained, we can obtain each slot machine through the bracket operator:

$($(".slot")[0]).html(slotOne);

jQuery will get the first slot machine and update its HTML to the correct number.

4. Add pictures to the slot machine. Each picture can be obtained through a different index.

$($('.slot')[0]).html('<img src = "' + images[slotOne-1] + '">');

 

<script>
var slotOne;
var slotTwo;
var slotThree;
function runSlots() {


var images = ["https://www.w3cschool.cn/statics/codecamp/images/9H17QFk.png", "https://www.w3cschool.cn/statics/codecamp/images/9RmpXTy.png", "https://www.w3cschool.cn/statics/codecamp/images/VJnmtt5.png"];

// 在这行的下面添加代码

$($('.slot')[0]).html('<img src = "' + images[slotOne-1] + '">');
$($('.slot')[1]).html('<img src = "' + images[slotTwo-1] + '">');
$($('.slot')[2]).html('<img src = "' + images[slotThree-1] + '">');


slotOne=Math.floor(Math.random()*(3-1+1))+1;
slotTwo=Math.floor(Math.random()*(3-1+1))+1;
slotThree=Math.floor(Math.random()*(3-1+1))+1;


if(slotOne==slotTwo && slotTwo==slotThree){
    
$('.logger').html("It's A Win");
return null;
}
// 在这行的上面添加代码
var logger = document.getElementsByClassName("logger")[0];
if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){
    logger.innerHTML = slotOne + " " + slotTwo + " " + slotThree;

}

logger.innerHTML += ' Not A Win';

return [slotOne, slotTwo, slotThree];
}

$(document).ready(function() {
 $('.go').click(function() {
 runSlots();
 });
 });
</script>
 
<div>
 <div class = 'container inset'>
 <div class = 'header inset'>
 <img src='/statics/codecamp/images/freecodecamp_logo.svg' alt='learn to code JavaScript at Free Code Camp logo' class='img-responsive nav-logo'>
 <h2>FCC Slot Machine</h2>
 </div>
 <div class = 'slots inset'>
 <div class = 'slot inset'>
 
 </div>
 <div class = 'slot inset'>
 
 </div>
 <div class = 'slot inset'>
 
 </div>
 </div>
 <br/>
 <div class = 'outset'>
 <button class = 'go inset'>
 Go
 </button>
 </div>
 <br/>
 <div class = 'foot inset'>
 <span class = 'logger'></span>
 </div>
 </div>
</div>

<style>
 .slot > img {
margin: 0!important;
height: 71px;
width: 50px;
 }
 .container {
 background-color: #4a2b0f;
 height: 400px;
 width: 300px;
 margin: 30px auto;
 border-radius: 4px;
 }
 .header {
 border: 2px solid #fff;
 border-radius: 4px;
 height: 55px;
 margin: 14px auto;
 background-color: #457f86
 }
 .header h2 {
 height: 30px;
 margin: auto;
 }
 .header h2 {
 font-size: 14px;
 margin: 0 0;
 padding: 0;
 color: #fff;
 text-align: center;
 }
 .slots{
 display: flex;
 background-color: #457f86;
 border-radius: 6px;
 border: 2px solid #fff;
 }
 .slot{
 flex: 1 0 auto;
 background: white;
 height: 75px;
 width: 50px;
 margin: 8px;
 border: 2px solid #215f1e;
 border-radius: 4px;
 text-align: center;
 }
 .go {
 width: 100%;
 color: #fff;
 background-color: #457f86;
 border: 2px solid #fff;
 border-radius: 2px;
 box-sizing: none;
 outline: none!important;
 }
 .foot {
 height: 150px;
 background-color: 457f86;
 border: 2px solid #fff;
 }
 
 .logger {
 color: white;
 margin: 10px;
 }
 
 .outset {
 -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);
 -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);
 box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);
 }
 
 .inset {
 -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);
 -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);
 box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);
 }
</style>






 

 

 

https://www.w3cschool.cn/minicourse/play/jscourse?cp=172&gid=0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_27009517/article/details/112233322