A, functions,
What is a function
Suppose we want to calculate the sum of integers 1 to 10, 5 to 12, and 14 to 35, respectively.
2. Function definition and call
1. Like variables, functions must be defined before they can be used.
Use the function keyword to define functions, which stands for “function”.
2. Function definition
function fun(){
// Function body statement
}
//function specifies a function. Fun indicates the function name, which must comply with the NAMING rules of JS identifiers.
// Inside the parentheses is a list of parameters. Parentheses must be written even if there are no parameters
Copy the code
Functional expression
var fun=function(){
// Function body statement
}
//function indicates an anonymous function
Copy the code
3. Function call
Executing all statements in the function body is called “calling a function.”
Calling a function is as simple as writing a pair of parentheses after the function name. Example: fun ();
4. Statement execution sequence
Execute in sequence. Statements in a function can only be executed after the function is called.
5. Enhancement of function declarations
Just like variable declarations can be promoted, function declarations can also be promoted
fun();
function fun(){
alert('Function executed');
}
// This function is promoted in the pre-parsing phase
Copy the code
If a function is defined by writing a function expression, there is no lifting feature.
fun();// Raise an error
var fun= function(){
alert('Function executed');
}
Copy the code
Function promotion first: function promotion first, then variable promotion.
3. Parameters of the function
1. Parameters are undetermined values in a function. The specific values of these parameters must be passed in when a function is called.
2. A function can have as many or as few parameters. A function can have no parameters or multiple parameters separated by commas.
4. Different numbers of parameters and arguments
5.arguments
Arguments inside a function denotes the list of arguments it receives, which is an array-like object.
Array-like objects: All attributes are a sequence of natural numbers starting at 0 and have a length attribute, similar to arrays. You can use square brackets to write subscripts to access an attribute value of an object, but cannot call array methods.
The return value of the function
1. The return keyword can be used to indicate the return value of a function.
2. Call a function that returns a value, which can be treated as a normal value and thus appear anywhere a value can be written.
3. Exit the function when you see a return: When invoking a function, the function will exit immediately once you see a return statement, and the execution authority is returned to the caller.
4. When combining if statements, there is no need to write else branches.
For example, write a function to determine whether a number is even
5. Function algorithm
A morning glory number is a three-digit number in which the factorial sum of each digit is exactly equal to itself. The ABC = a! + b! + c! Where ABC represents a three-digit number. Try to find all the morning glory numbers. To simplify the problem, encapsulate the factorial of a number as a function.
2.JavaScript has the built-in sort() method
Arrays can be sorted using the sort() method, which in turn takes a function.
A and b represent the first and last items in the array, respectively, and return any positive number if they need to be swapped. Otherwise return a negative number.
Functions are first-class citizens of JS and can be passed as arguments to another function.
arr.sort(function(a,b){
return a-b;
});
// Sort from smallest to largest; Pay attention to the format
Copy the code
6, recursion
1. An internal statement of a function can call the function itself, thus initiating an iteration of the function. In a new iteration, statements that call the function itself are executed, resulting in another iteration. When a function is executed once, no new iterations are made, and the function is returned layer by layer, recursively.
2. Recursion is a relatively advanced programming skill, which transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve.
Take the factorial of 4 for example
4. Recursive elements
Boundary conditions: Determine when a recursion terminates, also known as recursive exit.
Recursive patterns: How big problems break down into smaller problems, also called recursive bodies.
5
Fibonacci sequence: The Fibonacci sequence looks like this :1, 1, 2, 3, 5, 8, 13, 21. Do you see a pattern?
The terms with subscripts 0 and 1 are all values 1, starting with the terms with subscripts 2, each equal to the sum of the preceding two terms.
7, to achieve deep cloning
1. Review shallow clone:
Arrays cannot be cloned using statements such as var arr2 = arr1.
Shallow clone: Prepare an empty array of results, and then use the for loop to iterate through the array, pushing the iterated items into the array.
Shallow clones clone only one layer of the array. If the array is multi-dimensional, the cloned items will remain “unbroken”.
2. Implement deep cloning
Using recursive thinking, the overall idea is similar to shallow cloning, but with some changes: if the traversal to the item is a basic type value, then
Push the result array directly; If the iterated item is an array, the shallow clone operation is repeated.
Global and local variables
JavaScript is a functional scoped programming language: a variable has meaning only inside the function in which it was defined. (Local variable)
2. Global variables
If a variable is not defined inside any function, it is a global variable and can be accessed and changed within any function.
3. Masking effect
If the function also defines a variable with the same name as the global variable, the variables inside the function will “mask” the global variable.
4. Consider how variable declarations improve.
var a=10;
// 1: the local variable a is incremented by 1, a is undefined, and the result is NaN
// 2: reassign a to 5
function fun(){
a++;
var a=5;
console.log(a);/ / output 5
}
fun();
console.log(a);/ / output 10
Copy the code
5. Parameters are also local variables
var a=10;
function fun(a){
// The parameter a is also a local variable inside the function
a++;
console.log(a);/ / output 8
}
fun(7);
console.log(a);/ / output 10
Copy the code
6. Scope chain (1). First let’s recognize function nesting: a function can also be defined within a function. Similar to local variables, functions defined inside a function are local functions.
function fun(){
function inner(){// local function
console.log('hello');
}
inner();// Call an internal function
}
fun();// Call an external function
Copy the code
(2). In function nesting, a variable will look for its definition layer by layer from inside to outside.
var a=10,b=20;
function fun(){
var c=30;
function inner(){
var a=40;
var d=50;
// When using a variable, JS will start at the current level and work its way up
console.log(a,b,c,d);
}
inner();
}
fun();
// 40 20 30 50
Copy the code
(3). Global variables will be defined without var
var a=1,b=2;
function fun(){
// The letter c is not defined with the var keyword, so it becomes a global variable
c=3;
c++;
var b=4;
b++;
console.log(b);/ / 5
}
fun();
console.log(b);/ / 2
console.log(c);/ / 4
Copy the code
9, closures
1.JavaScript functions generate closures. Closures are a combination of the function itself and the state of the environment in which the function is declared.
// Create a function
function fun(){
// Define local variables
var name=Mooc Website;
// Returns a local function
return function(){ alert(name); }}// Call the outer function to get the inner function, which is received with the variable inn
var inn=fun();
// Define a global variable
var name='ABC';
Inn executes the inner function outside fun
inn();
// Export moOCs
Copy the code
2. What is a closure: A function can “remember” the context in which it was defined, even if the function is not called in the context in which it was defined.
3. Observe closures
In JavaScript, closures are created every time a function is created.
However, closure features often require the function to be executed “somewhere else” to be observed.
Closures are useful because they allow us to associate data with functions that operate on that data. This bears a slight resemblance to object-oriented programming.
5. Functions of closures: memorization, simulation of private variables.
1- Memorability: When a closure is generated, the state of the function’s environment is always kept in memory and will not be automatically cleared after the outer function is called. That’s the memorability of closures.
For example, create the temperature check function checkTemp(n) to check whether the temperature n is normal. The function returns a Boolean value.
However, different communities have different temperature detection standards, such as A community body temperature qualified line is 37.1 ° C, and B community body temperature qualified line is 37.3° C, how should be programmed?
function creatCheckTemp(standardTemp){
function checkTemp(n){
if(n<=standardTemp){
alert('Your temperature is normal.');
}else{
alert('Your temperature is up.'); }}return checkTemp;
}
// Create a checkTemp function with a standard line of 37.1 degrees
var checkTemp_A=creatCheckTemp(37.1);
// Create a checkTemp function with a standard line of 37.3 degrees
var checkTemp_B=creatCheckTemp(37.3);
checkTemp_A(37.2);
checkTemp_A(37.0);
checkTemp_B(37.2);
checkTemp_B(37.6);
Copy the code
Define a variable a that can only be used for specified operations (e.g., add 1, multiply 2), but not for other operations.
In Java, C++, etc., there is the concept of private attributes, but JavaScript can only be simulated with closures.
6. Do not abuse closures, which can cause performance problems for web pages or even memory leaks. A memory leak is when the dynamically allocated memory in a program is not released or cannot be released for some reason.
7. An interview question on closures
function addCount(){
var count=0;
return function(){
count=count+1;
console.log(count);
};
}
var fun1=addCount();
var fun2=addCount();
fun1();
fun2();
fun2();
fun1();
// Output 1, 1, 2, 2
//fun1 and fun2 do not affect each other
Copy the code
Execute IIFE immediately
1. What is the IIFE lIFE (LMMediately Invoked Function Expression) is a special JavaScript Function writing method that is Invoked immediately once defined.
2. Methods to form IIFE
Functions cannot be called with parentheses.
A function must be converted to a function expression before it can be called. Parentheses are the most common.
Assigning values to variables: When assigning values to variables requires more complex calculations (such as the if statement), lIFE is more syntactically compact.
var age = 42;
var sex = 'woman';
var title = (function () {
if (age < 18) {
return 'Little friend';
} else {
if (sex == 'male') {
return '先生';
} else {
return 'woman'; }}}) (); alert(title);Copy the code
LFE can change global variables to local variables in some situations (such as in the for loop), and the syntax is compact.
var arr=[];
for(var i=0; i<5; i++){ (function(i){
arr.push(function(){
alert(i);
});
})(i);
}
arr[0] (); arr[1] (); arr[2] (); arr[3] (); arr[4] ();// 0 1 2 3 4
Copy the code
11. Focus of the course
What is a function? What benefits do functions bring to programming?
2. Parameters and return values of the function
3. Function related algorithm questions
12. Difficult points
1. Recursion, recursive algorithm
2. Scopes and closures
3.lIFE
Second, the DOM
1. Basic concepts of DOM
DOM is a bridge between HTML and CSS.
DOM makes IT elegant for JS to manipulate HTML.
For example, in the following HTML structure, you now want to use JavaScript to insert a p tag pair after “milk” that says “Cola”.
2.DOM introduction: DOM(Document Object Model) is the interface of JavaScript to operate HTML documents, which makes Document operation very elegant and simple.
One of the biggest features of DOM is the representation of documents as a tree of nodes.
2. NodeType Common attribute value
The nodeType property of a node displays the specific type of the node.
NodeType value | The node type |
---|---|
1 | Element nodes, such as <p> and <div> |
3 | Text node |
8 | Comment node |
9 | The document node |
10 | DTD node |
3, the document
1. Access the element node
By “visiting” element nodes, we mean “getting” and “getting” element nodes on the page.
The first step in operating on a node is to get it.
Access to the element node host relies on the Document object.
2. Know the Document object
The Document object is the most important thing in the DOM; almost all of the DOM’s functionality is encapsulated in the Document object.
The Document object also represents the entire HTML document, which is the root of the DOM node tree.
The nodeType property of the document object has a value of 9.
Common methods for accessing element nodes
methods | function | compatibility |
---|---|---|
document.getElementById() | Get the element by id | IE6 |
document. getElementsByTagName() | Get an array of elements by tag name | IE6 |
document.getElementsByclassName() | Get an array of elements by class name | IE9 |
document.querySelector() | Get the element from the selector | Partially compatible with Internet Explorer 8 and fully compatible with Internet Explorer 9 |
document.queryselectorAll() | Get an array of elements through a selector | Partially compatible with Internet Explorer 8 and fully compatible with Internet Explorer 9 |
1. The getElementByld() document.getelementByld () function is to get the element node by id.
Note: The parameter is the id of the element node.
If there are elements with the same ID on the page, only the first one is retrieved.
No matter how deep an element is hidden, it can be found by id.
<div id="box1">I'm box one</div>
<div id="box2">I'm Box two</div>
Copy the code
var box1=document.getElementById('box1');
var box2=document.getElementById('box2');
Copy the code
2.getElementsByTagName()
The function of the getElementsByTagName() method is to get an array of nodes by tag names.
Matters needing attention:
Arrays are easy to traverse, allowing you to batch manipulate element nodes.
Even if there is only one node on the page with the specified label name, you get an array of length 1.
Any node element can also call the getElementsByTagName() method to get an element node of a class within it.
// get box1 first
var box1 = document.getElementById('box1');
// Get an array of p tags in box1
var ps_inbox1=box1.getElementsByTagName('p');
console.log(ps_inbox1);
Copy the code
3.getElementsByClassName()
The function of the getElementsByClassName() method is to get an array of nodes by class name.
Note: A node element can also call the getElementsByClassName() method to get an element node with a class name inside it.
4.querySelector()
The function of the querySelector() method is to get elements from the selector.
Matters needing attention:
The querySelector() method can only get one element on the page, or the first element if more than one element matches the criteria.
The querySelector() method is compatible from IE8 onwards, but CSS3 selector forms such as nth-Child () and :[SRC ^=’dog’] are well supported from IE9 onwards
5.querySelectorAll()
The querySelectorAll() method returns an array of elements via a selector.
Even if there is only one node on the page that matches the selector, you get an array of length 1.
5. Delayed operation
When testing DOM code, the JS code must generally be written after the HTML node, otherwise JS will not be able to find the corresponding HTML node.
You can use the window.onload = function() event to execute the specified code after the page is loaded.
<script>
// Add the onload event listener to the window object, onload indicates that the page is loaded.
window.onload = function () {
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
console.log(box1);
console.log(box2);
}
</script>
// You can write it inside head
Copy the code
6. Relationship of nodes
Relationship between | Consider all nodes | Only element nodes are considered |
---|---|---|
Child nodes | childNodes | children |
The parent node | parentNode | parentNode |
First child node | firstChild | firstElementChild |
The last child node | lastChild | lastElementChild |
Previous sibling node | previousSibling | previousElementSibling |
The latter sibling node | nextsibling | nextElementSibling |
Note that text nodes are also nodes
In the DOM, text nodes are also nodes, so be careful when using node relationships.
In the standard W3C specification, blank text nodes should also count as nodes, but there are compatibility issues in IE8 and previous browsers that do not treat empty text nodes as nodes.
7. Encapsulate node relation functions
1. Write common node relation functions
Writing IE6 is also compatible with the “find all element child node” function.
Writing IE6 is also compatible with the “find previous element sibling node” function.
How do I write a function to get all siblings of an element?
8 innerHTML&innerText.
1. How to change the contents of the element node:
You can change the contents of an element node using two related attributes :innerHTML and innerText.
The innerHTML property sets the content of a node in HTML syntax.
The innerText property can only set the content of a node in plain text.
9. Node operations
1. How to change the CSS style of element node:
Changing the CSS style of element nodes requires statements like this (CSS attributes are written as “humps”) :
2. How do I change the HTML attributes of an element
Standard W3C attributes, such as SRC, href, and so on, just need to be changed directly:
<img src="images/1.jpg" id="pic">
<a href="http://www.baidu.com" id="link">Go to baidu</a>
<script>
var oPic=document.getElementById('pic');
var oLink=document.getElementById('link');
oPic.src='images/2.jpg';
oLink.href='http://www.imooc.com';
oLink.innerText='Go to MOOC';
</script>
Copy the code
Properties that do not conform to W3C standards are set and read using setAttribute() and getAttribute().
<div id="box"></div>
<script>
var box=document.getElementById('box');
box.setAttribute('data-n'.10);
var n=box.getAttribute('data-n');
alert(n);
</script>
Copy the code
10. Create, remove, and clone nodes
1. Create a node
The document.createElement() method creates an HTML element with the specified tagname.
“Orphan Node” : The newly created node is “orphan node”, which means it is not mounted to the DOM tree and cannot be seen.
You must continue to insert orphan nodes into the DOM tree using the appendChild() or insertBefore() methods.
AppendChild () : Any nodes that are already on the DOM tree, you can call the appendChild() method, which can get orphan sections out
The dot is mounted inside it and becomes its last child node. (Append means append)
Syntax: parent node. AppendChild (orphan node);
InsertBefore () : Any node that is already in the DOM tree can call the insertBefore() method, which can mount the orphan node inside it as the node before its “benchmark child node.”
Syntax: parent node. InsertBefore (orphan node, benchmark node);
<div id="box">
<p>I'm paragraph 0</p>
<p>I'm the original paragraph 1</p>
<p>I'm the original paragraph 2</p>
</div>
<script>
var oBox=document.getElementById('box');
var oPs=oBox.getElementsByTagName('p');
// Create an orphan node
var oP=document.createElement('p');
// Set the inner text
oP.innerText='I'm new here';
/ / on the tree
// oBox.appendChild(oP);
oBox.insertBefore(oP,oPs[0]);
</script>
Copy the code
Exercise: Dynamically create a table with 20 rows and 12 columns.
<style>
td{
width: 20px;
height: 20px;
border: 1px solid # 000;
}
</style>
Copy the code
<table id="mytable"></table> <script> var mytable= document.getelementById ('mytable'); for(var i=0; i<20; Var tr=document.createElement('tr'); for(var j=0; j<12; Var td=document.createElement('td'); var td=document.createElement('td'); // let tr append td tag tr.appendChild(td); } // let mytable append tr to mytable.appendChild(tr); } </script>Copy the code
Please make the multiplication table
<style>
td{
width: 120px;
height: 30px;
border: 1px solid # 000;
}
</style>
Copy the code
<table id="mytable"></table>
<script>
// Create a multiplication table dynamically
var mytable=document.getElementById('mytable');
for(var i=1; i<=9; i++){// Create a new tr tag
var tr=document.createElement('tr');
for(var j=1; j<=i; j++){// Create a new TD tag
var td=document.createElement('td');
// Set td internal text
td.innerText=i+'乘'+j+'equal to'+(i*j);
// let tr append td tags
tr.appendChild(td);
}
// let mytable append tr tags
mytable.appendChild(tr);
}
</script>
Copy the code
2. Move the node
If you make a node that is already mounted to the DOM tree an appendChild() or insertBefore() argument, the node will
Has been moved.
Grammar:
AppendChild (node that already has a parent);
InsertBefore (node that already has a parent, benchmark child node);
This means that a node cannot be in two places in the DOM tree at once.
<div id="box1">
<p id="para">I am a paragraph</p>
</div>
<div id="box2">
<p>I am the original P tag of Box2</p>
<p>I am the original P tag of Box2</p>
<p>I am the original P tag of Box2</p>
<p>I am the original P tag of Box2</p>
</div>
<script>
var box1=document.getElementById('box1');
var box2=document.getElementById('box2');
var para=document.getElementById('para');
var ps_inbox2=box2.getElementsByTagName('p');
box2.appendChild(para);// Move to the back of box2
box2.insertBefore(para,ps_inbox2[0]);// Move to the front of box2
</script>
Copy the code
3. Delete the node
The removeChild() method removes a child node from the DOM.
Syntax: parent node. RemoveChild (to remove children);
A node cannot delete itself voluntarily; it must be deleted by the parent node.
<div id="box">
<p>I'm p node 0</p>
<p>I'm node one of P</p>
<p>I'm node two of P</p>
</div>
<script>
var box=document.getElementById('box');
var the_first_p=box.getElementsByTagName('p') [0];
box.removeChild(the_first_p);//p node 0 is deleted
</script>
Copy the code
4. Clone the node
The cloneNode() method can clone nodes, and the cloned nodes are “orphan nodes”.
Grammar:
Var orphan = old. CloneNode ();
Var orphan = old. CloneNode (true);
The argument is a Boolean value that indicates whether deep cloning is used: if true, all descendants of the node will also be checked
If false, only the node itself is cloned.
<div id="box1">
<ul>
<li>milk</li>
<li>coffee</li>
<li>coke</li>
</ul>
</div>
<div id="box2"></div>
<script>
var box1=document.getElementById('box1');
var box2=document.getElementById('box2');
// Get the array
var theul=box1.getElementsByTagName('ul') [0];
// Clone the node. Add true to clone the node
var new_ul=theul.cloneNode(true);
box2.appendChild(new_ul);
</script>
Copy the code
11. Event monitoring
1. What is “Event Listening”
DOM allows us to write JavaScript code to make HTML elements react to events.
What is an “event” : an interaction between a user and a web page; When the user clicks on the element; When the mouse moves over an element; When the text box
When the content is changed; When the keyboard is pressed in the text box; When the page has loaded and so on.
What is “event listening”? A “listening”, as the name suggests, allows the computer to detect at any time that an event has occurred, so that it can execute some program that the programmer has written in advance.
There are two main methods for setting event listeners: onxxx and addEventListener(). The difference between the two methods will be described in the “Event Propagation” lesson.
2. The easiest way to set up event listening:
The easiest way to set event listening for elements is to set their onxxx property, like this:
oBox.onclick = function () {
// When the box is clicked, the statement here is executed
}
Copy the code
3. Common mouse event monitoring:
The event name | Event description |
---|---|
onclick | When the mouse clicks on an object |
ondblclick | When you double click on an object (DBL: short for double) |
onmousedown | When a mouse key is pressed on an object |
onmouseup | When a mouse key is released on an object |
onmousemove | When a mouse key is moved over an object |
onmouseenter | When the mouse enters an object (similar event onmouseover) |
onmouseleave | When the mouse moves away from an object (similar event onmouseout) |
4. Common keyboard event monitoring
The event name | Event description |
---|---|
onkeypress | When a keyboard key is pressed (system buttons such as arrow keys and function keys are not recognized) |
onkeydown | When a keyboard key is pressed (the system button is recognized and occurs before onKeyPress) |
onkeyup | When a key on a keyboard is released |
5. Common form event listening
The event name | Event description |
---|---|
onchange | When the user changes the content of the domain |
onfocus | When an element is in focus (such as a TAB key or mouse click) |
onblur | When an element loses focus |
onsubmit | When the form is submitted |
onreset | When the form is reset |
oninput | When an element is being entered |
6. Common page event listening
The event name | Event description |
---|---|
onload | When the page or image is finished loading |
onunload | When the user exits the page |
More events about Windows or pages are covered in the BOM course
12. Event communication (often tested in interviews)
2. The spread of events: Actually, the spread of events is: first from the outside in, then from the inside out.
The onxxX notation only listens for the bubbling phase
3. The addEventListener () method
Dom0-level event listening: Only the bubbling phase can be listened on.
oBox.onclick=function(){};Copy the code
DOM2 level event listening:
oBox.addEventListener('click'.function(){
// This is the event handler
},true);
// The 'click' event name does not add on
// True listens for the capture phase, false listens for the bubble phase
Copy the code
4. Precautions The innermost element no longer distinguishes between capture and bubbling phases. The listener written first is executed, and the listener written later is executed.
If you set two or more events of the same name to an element, the dom0-level notation overwrites the first. The DOM2 level is executed sequentially.
13. Event Object (1)
1. What is an event object: An event handler provides a formal argument, which is an object that encapsulates the details of the event.
This parameter is usually represented by the word event or the letter E.
oBox.onmousemove=function(e){
// Object e is the "event object" of this event
};
Copy the code
2. Mouse position
attribute | Property description |
---|---|
clientX | Horizontal coordinates of the mouse pointer relative to the browser |
clientY | The vertical coordinates of the mouse pointer relative to the browser |
pageX | The horizontal coordinates of the mouse pointer relative to the entire web page |
pageY | The vertical coordinates of the mouse pointer relative to the entire web page |
offsetX | Horizontal coordinates of the mouse pointer relative to the event source element |
offsetY | The vertical coordinates of the mouse pointer relative to the event source element |
Event source elements:
Relative to the browser:
Full page:
Note: offsetX, clientX, if there are other containers in the box, the distance of that container will be displayed when in other containers.
14. Event Object (2)
1. E.charcode and E.kaycode properties:
The e. charcode property is commonly used in onKeyPress events to represent the “character code” of the character entered by the user.
The e.keycode property is commonly used in onKeyDown events and onKeyUp and represents the “key code” of the key that the user presses.
2. CharCode character code
character | Character code |
---|---|
The number ranges from 0 to 9 | 48 ~ 57 |
Uppercase letters A to Z | 65 ~ 90 |
Lowercase letters a to Z | 97 ~ 122 |
3. The keyCode key code
The keys | Key code |
---|---|
The number ranges from 0 to 9 | 48 to 57(Same as charCode key code) |
Letters from a to Z are of no size | 65 to 90(the same as the uppercase letters A to Z of the charCode keycode, whereas the keycode is case-insensitive and is 65 to 90) |
The four arrow keys ←↑→↓ | 37, 38, 39, 40 |
The enter key | 13 |
The blank space key | 32 |
4. Small cases:
Make a special effect: press the arrow keys to control the box movement on the page.
<style>
#box{
position: absolute;
top: 200px;
left: 200px;
width: 100px;
height: 100px;
background-color: orange;
}
</style>
Copy the code
<div id="box"></div>
<script>
var oBox=document.getElementById('box');
// The global variables t and l represent the top and left attributes of the box respectively
var t=200,l=200;
// Listen for the keypress event of the Document object, which represents when the user presses a key across the entire web page
document.onkeydown=function(e){
switch(e.keyCode){
case 37:
l-=3;
break;
case 38:
t-=3;
break;
case 39:
l+=3;
break;
case 40:
t+=3;
break;
}
// Change the style
oBox.style.left=l+'px';
oBox.style.top=t+'px';
}
</script>
Copy the code
15. Event Object (3)
1. E.p reventDefault () method:
The e.preventDefault() method is used to block the “default action” generated by the event. – The default action of an event must be blocked for special service requirements.
2. Case 1
Create a text box that allows the user to enter only lowercase letters and numbers. Other characters will have no effect.
Only numbers and lowercase letters can be entered: <input type="text" id="field">
<script>
// Input in English
var oField=document.getElementById('field');
oField.onkeypress=function(e){
console.log(e.charCode);
if(! (e.charCode>=48 && e.charCode<=57 || e.charCode>=97 && e.charCode<=122)) {// Block the browser's default behaviore.preventDefault(); }};</script>
Copy the code
3. Case 2
Make a mouse wheel event: Increment the number as the mouse moves down the box. Conversely, the number is reduced by 1.
The mousewheel event is onMouseWheel, whose event object E provides the deltaY attribute to indicate the direction of mouse scrolling, which returns a positive value when scrolling down and a negative value when scrolling up.
<div id="box"></div>
<h1 id="info">0</h1>
<script>
var oBox=document.getElementById('box');
var oInfo=document.getElementById('info');
// Global variables are the numbers displayed in info
var a=0;
// Add a mouse wheel event listener to the box
oBox.onmousewheel=function(e){
// Prevent the default event: when the user scrolls the mouse wheel in the box, the page's scroll bar will not scroll
e.preventDefault();
if(e.deltaY>0){
a++;
}else{
a--;
}
oInfo.innerText=a;
}
Copy the code
16. Event Object (4)
1. E. stopPropagation () method
The e.topPropagation () method is used to prevent further propagation of events. In some cases, it may be necessary to cut off the event and continue to propagate, otherwise the page effects will display bugs.
2. Small cases:
Make a pop-up layer: click the button to display the pop-up layer, click anywhere on the page, the pop-up layer is closed.
<style>
.modal{
width: 400px;
height: 140px;
background-color: # 333;
position: absolute;
top: 50%;
left: 50%;
margin-top: -70px;
margin-left: -200px;
display: none;
}
</style>
Copy the code
<button id="btn"</button><div class="modal" id="modal"></div>
<script>
var oBtn=document.getElementById('btn');
var oModal=document.getElementById('modal');
// When the button is clicked, the layer is displayed
oBtn.onclick=function(e){
// Prevent the event from propagating to the document
e.stopPropagation();
oModal.style.display='block';
};
// The pop-up layer closes when clicking on any part of the page
document.onclick=function(){
oModal.style.display='none';
};
// When clicking inside the pop-up layer, you cannot close the pop-up layer, so you should prevent the event from propagating
oModal.onclick=function(e){
// Prevent the event from propagating to the document
e.stopPropagation();
};
</script>
Copy the code
17, event delegation (1) (Interview often test)
1. Add event listeners in batches
Title: There is an unordered list on the page<ul>It has 20 inside<li>Element, please add click event listener to them in batches, achieve the effect: click which<li>Element, which one<li>The element becomes redCopy the code
// Write loop statements to add listeners to elements in batches
for(var i=0; i<lis.length; i++){ lis[i].onclick=function(){
// In this function, this represents the element to be clicked on. This covers the context of the function, which we will cover in the object-oriented course
this.style.color='red'; }}Copy the code
2. Add event listeners in batches
Each event listener registration consumes a certain amount of system memory, and adding events in batches can cause too many listeners and consume a lot of memory.
In fact, each
3. Add element dynamic binding event:
Title: There is an unordered list on the page<ul>It doesn't have any inside<li>Element, please make a button, click this button to add one<li>Elements. And ask for each increment<li>The element also has to have click events to listen for which effect to click on<li>Element, which one<li>The element becomes redCopy the code
<button id="btn"> Press I to add a new li entry </button><ul id="list"></ul>
<script>
var oBtn=document.getElementById('btn');
var oList=document.getElementById('list');
var lis=oList.getElementsByTagName('li');
// Button click events
oBtn.onclick=function(){
// Create a new li list item, orphan node
var oLi=document.createElement('li');
oLi.innerHTML='I'm a list item';
/ / on the tree
oList.appendChild(oLi);
// Add an onclick event listener to the newly created li node
oLi.onclick=function(){
this.style.color='red';
};
};
</script>
Copy the code
4. Issues with dynamically binding events:
New elements must have event listeners added separately. Event listeners cannot be obtained automatically.
A large number of event listeners and a large number of event handlers generate a large amount of memory consumption.
18. Event Delegation (2)
1. Event Delegation:
The event bubble mechanism is used to delegate descendant element events to ancestor elements
2. The e.target and E.currenttarget properties
Event delegates are usually required in conjunction with the E.target property
attribute | Property description |
---|---|
target | The earliest element that triggers this event, the event source element |
currentTarget | Element to which the event handler is attached |
<ul id="list">
<li>The list items</li>
<li>The list items</li>
<li>The list items</li>
</ul>
<script>
var oList=document.getElementById('list');
oList.onclick=function(e){
e.target.style.color='red';
}
</script>
Copy the code
3. Usage scenarios of event delegation:
Using event delegates can reduce memory overhead when there are a large number of similar elements to which event listeners need to be added in bulk.
When there are dynamic element nodes on the tree, the use of event delegate allows the new element on the tree to have event listeners.
What’s the difference between onMouseEnter and onmouseOver, which both mean “mouse in”? A: OnMouseEnter does not bubble, onMouseOver bubbles.
A note of caution when using event delegates: You cannot delegate non-bubbling events to an ancestor element.
Innermost elements cannot have additional inner elements, such as:
19. Timer
1. The timer setInterval() function can call a function repeatedly with a fixed interval between calls.
The setInterval() function can accept arguments 3 and 4….. Parameters, which are passed to the function in order.
Named functions can also be passed setlnterVal:
2. Clear timer:
The clearInterval() function clears a timer.
<h1 id="info">0</h1>
<button id="btn1">start</button>
<button id="btn2">suspended</button>
<script>
var oInfo=document.getElementById('info');
var oBtn1=document.getElementById('btn1');
var oBtn2=document.getElementById('btn2');
var a=0;
// Global variables
var timer;
oBtn1.onclick=function(){
To prevent timer stacking, we should clear the timer before setting it
clearInterval(timer);
// Change the global variable timer to a timer entity
timer=setInterval(function(){
oInfo.innerText=++a;
},1000);
};
oBtn2.onclick=function(){
clearInterval(timer);
};
</script>
Copy the code
20. Delay device
The setTimeout() function sets a timer that will execute the function once the specified time is up.
2. Clear the delay timer
The clearTimeout() function clears the delayer, much like clearInterval().
3. Learn about asynchronous statements
SetInterval () and setTimeout() are two asynchronous statements.
Asynchronous: Does not block the CPU from continuing to execute other statements, and when the asynchrony is complete, a “callback” is executed.
21, use timer to achieve animation
1. It is inconvenient to use timer to realize animation:
(1) It is not convenient to calculate the step length according to the total animation time
(2) The direction of movement should be set positive and negative
(3) It is difficult to stack multiple movements (for example, a square moves on one side — one side becomes circular)
JS and CSS3 combine to achieve animation
1. We know that CSS3 can animate the transition property.
JavaScript can easily animate elements using the Transition property of CSS3.
JS and CSs3 combined animation to avoid the shortcomings of timer animation.
2. Function throttling
Function throttling: a function executed once is allowed to be executed twice only after a specified execution period.
Function throttling is easy to implement with the help of the setTimeout() delay timer.
3. The formula
23. Animation effect development 1 — Seamless continuous rolling effects
2. Code:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>* {margin: 0;
padding: 0;
}
.box{
width: 1000px;
height: 130px;
border: 1px solid # 000;
margin: 50px auto;
overflow: hidden;
}
.box ul{
list-style: none;
/* Set it large so that li can float */
width: 5000px;
position: relative;
}
.box ul li{
float: left;
margin-right: 10px;
}
</style>
</head>
<body>
<div id="box" class="box">
<ul id="list">
<li><img src="images/number/0.png" alt=""></li>
<li><img src="images/number/1.png" alt=""></li>
<li><img src="images/number/2.png" alt=""></li>
<li><img src="images/number/3.png" alt=""></li>
<li><img src="images/number/4.png" alt=""></li>
<li><img src="images/number/5.png" alt=""></li>
</ul>
</div>
<script>
var box=document.getElementById('box');
var list=document.getElementById('list');
// Copy all li again
list.innerHTML+=list.innerHTML;
// The left value of the current list
var left=0;
// Timer, global variable
var timer;
move();
// Animation is wrapped as a function
function move(){
// set the table to close first to prevent animation accumulation
clearInterval(timer);
timer=setInterval(function(){
left-=4;
/ / acceptance
if(left<=-1260){
left=0;
}
list.style.left=left+'px';
},20);
}
// Mouse enters the stop timer
box.onmouseenter=function(){
clearInterval(timer);
};
// Mouse away to continue timer
box.onmouseleave=function(){
move();
}
</script>
</body>
</html>
Copy the code
24. Animation effect development 2 — Special effects of running lantern wheel broadcast map (asked in interview)
1, the principle of
2, code,
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.carousel {
width: 650px;
height: 360px;
border: 1px solid # 000;
margin: 50px auto;
position: relative;
overflow: hidden;
}
.carousel ul {
list-style: none;
width: 6000px;
position: relative;
left: 0px;
transition: left .5s ease 0s;
}
.carousel ul li {
float: left;
}
.carousel .leftbtn {
position: absolute;
left: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background-color: rgb(28.180.226);
border-radius: 50%;
}
.carousel .rightbtn {
position: absolute;
right: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background-color: rgb(28.180.226);
border-radius: 50%;
}
</style>
</head>
<body>
<div class="carousel">
<ul id="list">
<li><img src="images/beijing/0.jpg" alt=""></li>
<li><img src="images/beijing/1.jpg" alt=""></li>
<li><img src="images/beijing/2.jpg" alt=""></li>
<li><img src="images/beijing/3.jpg" alt=""></li>
<li><img src="images/beijing/4.jpg" alt=""></li>
</ul>
<a href="javascript:;" class="leftbtn" id="leftbtn"></a>
<a href="javascript:;" class="rightbtn" id="rightbtn"></a>
</div>
<script>
// Get the button and ul, ul moves as a whole
var leftbtn = document.getElementById('leftbtn');
var rightbtn = document.getElementById('rightbtn');
var list = document.getElementById('list');
// clone the first image
var cloneli = list.firstElementChild.cloneNode(true);
list.appendChild(cloneli);
// The current ul is displayed to the number of pages, starting from 0
var idx = 0;
/ / throttle lock
var lock = true;
// The right button listens
rightbtn.onclick = function () {
// Check the lock status
if(! lock)return;
lock = false;
// Add transition to list. CSS has already added?? This is because the last image will remove the transitions
list.style.transition = 'left .5s ease 0s';
idx++;
if (idx > 4) {
// Set a delay timer. The function of the delay timer is to instantly pull ul back to 0. The purpose of the delay timer is to let the transition animation end
setTimeout(function () {
// Cancel transitions because you want teleportation, not gollum back
list.style.transition = 'none';
list.style.left = 0;
idx = 0;
}, 500);
}
list.style.left = -idx * 650 + 'px';
// function throttling
setTimeout(function () {
lock = true;
}, 500);
}
// The left button listens
leftbtn.onclick = function () {
if(! lock)return;
lock = false;
// Check if it is the 0th card, if so, immediately replace the false card with the true one
if (idx == 0) {
// Cancel transitions because you want teleportation, not gollum
list.style.transition = 'none';
// Teleport directly to the last fake image
list.style.left = -5 * 650 + 'px';
// Set a delay timer, the delay time can be 0 ms, although it is 0 ms, but let us transition first instant cancel, then add
setTimeout(function () {
/ / add the transition
list.style.transition = 'left .5s ease 0s';
// idx is changed to the real last card
idx = 4;
list.style.left = -idx * 650 + 'px';
}, 0);
} else {
idx--;
list.style.left = -idx * 650 + 'px';
}
// function throttling
setTimeout(function () {
lock = true;
}, 500);
}
</script>
</body>
</html>
Copy the code
25. Animation effect development 3 — Special effects of breathing rotation
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.carousel {
width: 650px;
height: 360px;
border: 1px solid # 000;
margin: 50px auto;
position: relative;
}
.carousel ul {
list-style: none;
}
.carousel ul li {
position: absolute;
top: 0;
left: 0;
/* Transparency is 0 */
opacity: 0;
transition: opacity 1s ease 0s;
}
/* Only the first transparency is 1 */
.carousel ul li:first-child {
opacity: 1;
}
.carousel .leftbtn {
position: absolute;
left: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background-color: rgb(28.180.226);
border-radius: 50%;
}
.carousel .rightbtn {
position: absolute;
right: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background-color: rgb(28.180.226);
border-radius: 50%;
}
</style>
</head>
<body>
<div class="carousel">
<ul id="list">
<li><img src="images/beijing/0.jpg" alt=""></li>
<li><img src="images/beijing/1.jpg" alt=""></li>
<li><img src="images/beijing/2.jpg" alt=""></li>
<li><img src="images/beijing/3.jpg" alt=""></li>
<li><img src="images/beijing/4.jpg" alt=""></li>
</ul>
<a href="javascript:;" class="leftbtn" id="leftbtn"></a>
<a href="javascript:;" class="rightbtn" id="rightbtn"></a>
</div>
<script>
// Get the button and ul, ul moves as a whole
var leftbtn = document.getElementById('leftbtn');
var rightbtn = document.getElementById('rightbtn');
var list = document.getElementById('list');
var lis = list.getElementsByTagName('li');
// Which graph is displayed now
var idx=0;
/ / throttling
var lock=true;
/ / right button
rightbtn.onclick=function(){
// Determine throttling
if(! lock)return;
lock=false;
// Idx has not been changed yet, the idX is the old image, the old image fades out
lis[idx].style.opacity=0;
idx++;
if(idx>4)idx=0;
// Change the idx, then the idX is the new image, the new image fades in
lis[idx].style.opacity=1;
// When the animation is over, unlock the lock
setTimeout(function(){
lock=true;
},1000);
}
/ / the left button
leftbtn.onclick=function(){
// Determine throttling
if(! lock)return;
lock=false;
// Idx has not been changed yet, the idX is the old image, the old image fades out
lis[idx].style.opacity=0;
idx--;
if(idx<0)idx=4;
// Change the idx, then the idX is the new image, the new image fades in
lis[idx].style.opacity=1;
// When the animation is over, unlock the lock
setTimeout(function(){
lock=true;
},1000);
}
</script>
</body>
</html>
Copy the code
26. Key points
1. What are the methods for accessing element nodes?
2. What are the relationships between nodes?
3. What are common node operations?
4. How to create, remove, and clone nodes?
5. What are event capture and bubbling? How should it be set up? (Often tested in interviews)
6. What is event delegation? When do you use event delegates? (Often tested in interviews)
7. Use timer and CSS3 transition to achieve animation
3. BOM basis
1. Window object
1. What is BOM:
BOM (Browser Object Model) is the interface between JS and Browser window.
Special effects related to browser resizing and scrollbar scrolling all rely on BOM technology
2. The window object
The window object is the window in which the JS script is currently running, and this window contains the DOM structure. The window.document property is the Document object.
In tabbed browsers, each TAB has its own Window object; That is, the tabs of the same window do not share a Window object.
3. Global variables are window properties
Global variables become properties of the window object.
This means that multiple JS files share global scope, i.e. js files have no scope isolation.
4. Built-in functions are generally window methods, such as setlnterVal () and alert()
5. Window size related attributes
attribute | meaning |
---|---|
innerHeight | The height of the content area of the browser window, including the horizontal scroll bar (if any) |
innerwidth | The width of the content area of the browser window, including the vertical scroll bar (if any). |
outerHeight | The outer height of the browser window |
outerwidth | The outer width of the browser window |
Not the width of the window containing the scroll bar, want to use the document. The documentElement. ClientWidth
The resize event is triggered when the window size changes. You can use window.onresize or window.addeventListener (‘resize’) to bind event handlers.
window.onresize=function(){
var root=document.documentElement;
console.log('Window size changed :',root.clientWidth,root.clientHeight);
}
Copy the code
7. Rolled height The window.scrollY property represents the value of pixels that have been rolled vertically.
8. Document has dynamic height. DocumentElement. ScrollTop properties also said window scroll height. var scrollTop = window.scrollY|| document.documentElement.scrollTop;
Document. The documentElement. ScrollTop is not read-only, window. ScrollY is read-only.
Can the document. The documentElement. ScrollTop = 0 is used to return to the top.
The scroll event is triggered when a window is rolled. You can use window.onscroll or window.addEventListener(‘scroll’) to bind event handlers.
2. Navigator object
The window.navigator property retrieves the Navigator object, which contains the properties and identity of the browser in which the user is active.
attribute | meaning |
---|---|
appName | Browser official name |
appVersion | Browser Version |
userAgent | User agent for the browser (with kernel and shell information) |
platform | User operating system |
3. History object
The window.history object provides an interface to manipulate the browser session history. A common practice is to simulate the browser back button
<h1>8-history method page </h1><button id="btn">The fallback</button>
<a href="javascript:history.back();">The fallback</a>
<script>
var btn=document.getElementById('btn');
btn.onclick=function(){
// history.back();
history.go(-1);
}
</script>
Copy the code
4. Location object
1. Window. location identifies the current url. You can assign this attribute to the browser to jump to the page.
Such as:
window. location = 'http: //www .imooc.com ' ;
window.location.href = 'http: / /www.imooc.com' ;
You can call the Reload method of location to reload the current page, with the true parameter forcing a load from the server.
window.location.reload(true);
3.GET query parameter window.location.search property is the current browser GET query parameter such as https://www.imooc.com/?a=1&b=2 console.log(window. location.search) ;
5. BOM special effects development
1. Return to the top button Return to the top of the principle: to change the document. The documentElement. ScrollTop properties, through the timer to gradually change the value, will return to the top in animation form.
<style>
body{
height: 5000px;
background-image: linear-gradient(to bottom,blue,green,yellow);
}
.backtotop {
width: 60px;
height: 60px;
background-color: rgba(255.255.255.6);
position: fixed;
bottom: 100px;
right: 100px;
/* Small hand */
cursor: pointer;
}
</style>
Copy the code
<div class="backtotop" id="backtotopBtn"> return to top </div><script>
var backtotopBtn=document.getElementById('backtotopBtn');
var timer;
backtotopBtn.onclick=function(){
// set table first
clearInterval(timer);
// Set the timer
timer=setInterval(function(){
// Keep scrollTop down
document.documentElement.scrollTop-=100;
// The timer must stop
if(document.documentElement.scrollTop<=0) {clearInterval(timer); }})};</script>
Copy the code
2. Floor navigation small effect
DOM elements have the offsetTop attribute, which represents the vertical distance from the element to the locating ancestor element.
Locating ancestor element: The element closest to the ancestor that has the locating attribute.
Note: when using this attribute, all ancestor elements should not have a position, which is not useful.
Remember to look at the code
6. Focus of the course
1. What are the window related attributes? 2. What is the window roll event? How do I get the roll value? 3. Use common properties and methods for Navigator objects, History objects, and Location objects.