Basic JavaScript learning

Keywords: JSON IE Javascript Mobile

Origin of note learning: Top 100 projects of Duyi education Web front end

Interaction: do an operation on the page, etc., and then it returns a feedback

Binding events
Note: an event can only be bound to one processing function, which is basically equivalent to being written in html between lines
Namely:

<div style="width:100px;height:100px;background-color:red;οnclick='console.log('a')'"></div>
//The same as:
<script>
	var div=document.getElementsByTagName('div')[0];
	//handle
	div.onclick=function (){
		console.log("a");
	}
</script>

Another way to bind events:
For example:

Div.addeventlistener (event type, handler, false);

The above method of binding events can bind multiple (addresses are different), but cannot bind the same function multiple times and execute in the order of binding

The third way to bind events: (unique to IE9)

div.attachEvent('on'+Event type, handler);
div.attachEvent('onclick',function (){});

You can bind multiple (different addresses), bind the same function multiple times, and execute in the order of binding

Using native js, addEventListener(), bind a click event to each li and output their order

<ul>
    <li>a</li>
    <li>a</li>
    <li>a</li>
    <li>a</li>
</ul>
<script>
    var li=document.getElementsByTagName('li');
    var len=li.length;
    // for(var i=0;i<len;i++){
    //     li[i].addEventListener('click',function () {
    //         console.log(i);
    //     },false);
    // }
    //Note that the above writing method will cause problems and form closures; because events are only bound to the corresponding elements, but at least they will be executed after the for function. At this time, i is already 4, so no matter which one you click, it is 4
    for(var i=0;i<len;i++){
        (function (j) {
            li[j].addEventListener('click',function () {
                console.log(j);
            },false);
        }(i))
    }
</script>

Note: when binding an event, once the event appears in the loop, you must consider whether to form a closure!

ele. ο nclick = this in function() {} and obj.addEventListener() points to itself.
But this in attachEvent points to window.

Encapsulate addEvent()

<div style="width: 100px;height: 100px;background-color: red"></div>

<script>
    var div=document.getElementsByTagName('div')[0];
    //Parameters: process object, process type, process function
    function addEvent(elem,type,handle) {
        if(elem.addEventListener){
            elem.addEventListener(type,handle,false);
        }else if(elem.attachEvenet){
            elem.attachEvenet('on'+type,function () {
                handle.call(elem);   //Because attachEvenet's this pointer points to window
            })
        }else {
            elem['on'+type]=handle;
        }
    }

</script>

Unbind event

div.onclick=function () {
        console.log('a');
    }
    div.onclick=null;

Note: cannot clear if anonymous function is bound

div.addEventListener('click',test,false)
    function test() {
        console.log('a');
    }
    div.removeEventListener('click',test,false);
 div.attachEvent('onclick',test);
    function test() {
        console.log('a');
    }
div.detachEvent('onclick',test);

Event processing model -- event bubbling and capturing
Event bubbling:
The elements of nesting relationship in structure (non visual) will have the function of event bubbling, that is, the nesting relationship of the same event from child element bubbling to parent element (bottom-up) code
Event capture
Structural (non visual) nested elements have the function of event capture, that is, the same event is captured from the parent element to the child element (event source element) (top-down)
IE did not capture events
Trigger order: first capture, then bubble (when binding two functions)

Examples of event bubbling:

<style>
        .wrapper{
            height: 300px;
            width: 300px;
            background-color: red;
        }
        .content{
            width: 200px;
            height: 200px;
            background-color: green;
        }
        .box{
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
</style>

<!--<div style="width: 100px;height: 100px;background-color: red"></div>-->

<div class="wrapper">
    <div class="content">
        <div class="box"></div>
    </div>
</div>
<script>
    var wrapper=document.getElementsByTagName('div')[0];
    var content=document.getElementsByTagName('div')[1];
    var box=document.getElementsByTagName('div')[2];
    wrapper.addEventListener('click',function () {
        console.log('wrapper');
    },false);
    content.addEventListener('click',function () {
        console.log('content');
    },false);
    box.addEventListener('click',function () {
        console.log('box');
    },false);

</script>

Turn all false above to true, and it will become event capture
The sequence of event capture and event bubble is just the opposite.

focus, blur, change, submit, reset, select and other events do not bubble

Cancel bubbling and block default events
Cancel bubble
W3C standard event.stopPropagation();
stopPropagation in the event object can be de bubbled
event.cancelBubble=true

<div style="width: 100px;height: 100px;background-color: red"></div>
<script>
    var div=document.getElementsByTagName('div')[0];
    document.onclick=function (ev) {
        console.log('Do you have nothing to do~');
    }
    div.onclick=function (e) {
        e.stopPropagation();
        //e.cancelBubble=true;
        this.style.backgroundColor='green';
    }

</script>

Encapsulate the stopBubble function

function stopBubble(event) {
        if(event.stopPropagation){
            event.stopPropagation();
        }else{
            event.cancelBubble=true;
        }
    }

Block default events
Default events - form submission, a tag jump, right-click menu, etc
1.return false an event registered as an object property takes effect
2.event.preventDefault() W3C annotation, incompatible with IE9
3.event.returnValue=false; IE compatible

Block right-click default menu events

document.oncontextmenu=function (ev) {
        console.log('a');
        //ev.preventDefault();
        ev.returnValue=false;
        //return false;
    }

Encapsulate cancelHandler

 function cancelHandler(ev) {
        if(ev.preventDefault){
            ev.preventDefault();
        }else{
            rv.returnValue=false;
        }
    }

Event object, e.window in IE browser

var event=e||e.window;

The event object has a property on it: event source object
Event source object:
event.target Firefox only has this
event.srcElement IE only this
chrome has both.
Compatible writing:

var target=event.target||event.srcElement;

Example of event source object usage:
Event delegation
What should have been done by 'son' was done by 'father'
Using event bubbling and event source objects for processing
Advantage:
1. Performance does not need to loop all elements to bind events one by one
2. Flexibility: no need to rebind events when there are new child elements

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
</ul>
<script>
    var div=document.getElementsByTagName('div')[0];
//Principle: event bubbling, event source event
    var ul=document.getElementsByTagName('ul')[0];
    ul.onclick=function (ev) {
        var event=ev||ev.event;
        var target=ev.target||ev.srcElement;
        console.log(target.innerText);
    }
</script>

Event classification
Mouse event

Method explain
click Click events
mousedown Mouse click
mousemove Mouse movement
mouseup Mouse bounce
contextmenu Right click to generate menu event
mouseover When the mouse moves in
mouseout When the mouse moves out
mouseenter When the mouse moves in
mouseleave When the mouse moves out

Use button to distinguish mouse button 0/1/2 mousedown and mouseup (event: e.button is 0 left key e.button==2 right key)
According to the DOM 3 standard, the click event can only listen to the left key, and the mouse key can only be judged by mousedown and mouseup

Drag and drop mouse

<div style="width: 100px;height: 100px;background-color: red;position:absolute;left: 0;top: 0;"></div>

<script>
    var div=document.getElementsByTagName('div')[0];
    var disX,
        disY;
    div.onmousedown=function (e) {
        disX=e.pageX-parseInt(div.style.left);
        disY=e.pageY-parseInt(div.style.top);
        document.onmousemove=function (e) {
            var event=e||window.event;
            // console.log(e.pageX+" "+e.pageY);
            div.style.left=e.pageX-disX+'px';
            div.style.top=e.pageY-disY+'px';
        }
        document.onmouseup=function () {
            div.onmousemove=null;
        }
    }

</script>

Encapsulate as a function

function drag(elem) {
        var disX,
            disY;
        addEvent(elem,'mousedown',function (e) {
            var event=e||window.event;
            disX=event.clientX-parseInt(getStyle(elem,'left'));
            disY=event.clientY-parseInt(getStyle(elem,'top'));
            addEvent(document,'mousemove',moudeMove);
            addEvent(document,'mouseup',mouseUp);
            stopBubble(event);
            cancelHandler(event);
        });

        function mouseMove(e) {
            var event=e||window.event;
            elem.style.left=event.clientX-disX+'px';
            elem.style.top=event.clientY-disY+'px';
        }
        function mouseUp(e) {
            var event=e||window.event;
            removeEvent(document,'mousemove',mouseMove);
            removeEvent(document,'mouseup',mouseUp);

        }
    }

Keyboard events

Method Explain
keydown Any keyboard key
keyup Release keyboard key
keypress Press the character key to return to ASCII code, which can be converted into corresponding characters
touchstart Mobile terminal
touchmove Mobile terminal
touchend Mobile terminal

keydown>keypress>keyup
The keyboard will be triggered continuously without up

keypress can detect character type keys and know what has been pressed:

document.onkeypress=function (ev) {
        console.log(String.fromCharCode(ev.charCode));
    }

Text action event
input, focus, blur, change

var input=document.getElementsByTagName('input')[0];
  //input.οninput=function () {
  //   console.log(this.value);
  //}
    input.onchange=function () {
        console.log(this.value);
    }
<style>
        input{
            border: 1px solid black;
        }
</style>
<input type="text" style="color: #999;" value="enter one user name"
       onfocus="if(this.value=='enter one user name'){this.value=''};this.style.color='#424242'"
       onblur="if(this.value==''){this.value='enter one user name'};this.style.color='#999'"></input>

Form action class (event on window)
Scroll (triggered when the scroll bar scrolls) load

 window.onscroll=function (ev) {
        console.log(this.pageXOffset+" "+this.pageYOffset);
    }

json
In short, it's the object
There must be a format for front-end and back-end data communication, and now the format of data transmission is the object
But there are different purposes. Objects are used locally and json is used for transmission.)

However, it's impossible to transfer the object during the real transfer. Only the format of binary text can be transferred. In fact, it's a string, but this string is a json format string.

How to change an object into a string in json format:
JSON.parse(); string->json
JSON.stringify(); json ->string

 var obj={
        "name":'abc',
        "age":'20'
    }
    //To pass the above object to the and backend:
    var str=JSON.stringify(obj);
    console.log(str);
    //Accept to use
    JSON.parse(str);  //Resolve str to object

When the browser recognizes the html code, it will put each node in the html code on a domTree. When drawing this tree, it will meet the depth first principle -- dom node parsing. The end of parsing does not mean the end of loading. ——Asynchronous (simultaneous)
After the domTree is parsed, it will wait for the cstree to finish. When both domTree and cstree are parsed, the two will be spliced together to generate a randerTree. After the randerTree is generated, the rendering engine will start to draw the page according to the randerTree.

Optimization: when the domTree is changed, it means that the entire randerTree needs to be changed, which will * * waste efficiency, * * so optimization is needed. Reconstruction of this randerTree -- reflow
What causes reflow?
dom node delete, add. display none – > block, offset width, ofsetLeft (real-time)

Repaint - repaint, low efficiency and waste

We want to load js asynchronously. Generally, this js does not modify css, so we want it to load asynchronously to improve efficiency.
There are three ways to load js asynchronously:
1.defer is loaded asynchronously, but will not be executed until the dom document is completely parsed. Only IE can use it, or you can write the code inside.

<script type="text/javascript" src="tools.js" defer="defer"></script>

2.async loads asynchronously and executes after loading. async can only load external scripts, not js in the script tag.
1.2 do not block the page during execution

<script type="text/javascript" src="tools.js" async="async"></script>

3. Create script and insert it into DOM. After loading, callBack is the most commonly used method. It has good compatibility and can also be loaded on demand

<script>
	var script=document.creatElement('script');
	script.type="text/javascript";
	//Asynchronous Download
	script.src="tools.js";
	//This will only be executed if you write
	document.head.appendChild(script);
</script>

Make sure you can perform after downloading: load()

<script>
	var script=document.creatElement('script');
	script.type="text/javascript";
	//Asynchronous Download
	script.src="tools.js";
	
	if(script.readyState){
		script.onreadystatechange=function () {
		if(script.readyState=='completed'||script.readyState=='loaded'){
			test();
		}
	}
	}else{
		script.onload=function () {
		test();
	}
	}
	

	script.onload=function () {
		test();
	}
	//But the above method of judging whether the download is completed is not available for IE
	//IE's own method
	script.onreadystatechange=function () {
		if(script.readyState=='completed'||script.readyState=='loaded'){
			test();
		}
	}
	document.head.appendChild(script);
</script>

Encapsulate as function: loadScript

function loadScript(url,callback) {
	var script=document.creatElement('script');
	script.type='text/javascript';
	
	if(script.readyState){
		script.onreadystatechange=function (){
			if(script.readyState=='complete'||script.readyState=='loaded'){
				callback();
			}
		}
	}else{
		script.onload=function () {
			callback();
		}
	}
	//Bind events before loading
	script.src=url;
	document.head.appendChild(script);
}

js load timeline
1. Create the Document object and start parsing the web page. This stage: document.readyState='loading '
2. When encountering link external css, create a thread to load and continue to parse the document
3. When encountering script external js, and async and defer are not set, the browser loads and blocks, waits for js to load and execute the script, and then continues to parse
4. When script external js is encountered and async and defer are set, the browser creates a thread to load and continues to parse the document
For the script with async attribute, the script is executed immediately after loading (document.write() is forbidden asynchronously)
5. In case of img, the dom structure should be parsed normally, and then the browser should load src asynchronously and continue to parse the document
6. When document parsing is completed, document.readyState='interactive '
7. After the document is parsed, all scripts with defer set will be executed in order.
8. The document object triggers the DOMContentLoaded event, which also marks the transition of program execution from the synchronous script execution phase to the time driven phase
9. When all async scripts are loaded and executed, and img is loaded, document.readyState = 'complete',
10. From then on, handle user input, network events, etc. in an asynchronous response mode

Published 73 original articles, won praise 7, visited 2574
Private letter follow

Posted by sbrinley on Tue, 04 Feb 2020 08:06:35 -0800