编程知识 cdmana.com

Browser built in objects / events

Browser is a javascript The runtime environment for , It's based on js Parser at the same time , Added a lot of environmental content . We put the common ones into use js The content controlled by this language is called a js Operating environment , Common operating environments are nodejs, Browsers and applets , Some Internet of things devices, etc . All operating environments must have a js Interpreter , At the interpreter level, it conforms to ECMAScript standard , Defined js Language level things like keywords , Grammar and so on .

In every environment , It will also be based on js Develop some features in the current environment , for example nodejs Medium global object ,process object , In the browser environment window object ,document Object etc. , These belong to the operating environment js Based on the content .require yes nodejs Content in a unique operating environment , Cannot be used on the browser side .

Browser built in objects

window

window Represents the global scope in the browser , All variables and contents declared under global scope will eventually become window Properties of objects, such as :

var num = 123;
console.log(window.num) //123
 Copy code 

Accessing undeclared variables is , If direct access , Will report a mistake , And if you use window Visit , It's like accessing through objects , Returns the undefined.

var name = oldName;   //  Report errors Uncaught ReferenceError: oldName is not defined
var name2 = window.oldName; // undefined
 Copy code 

setTimeout and setInterval

They can both take two parameters , The first parameter is a callback function , The second parameter is the time to wait for execution , At the end of the waiting time , It will put the callback function into event loop Implementation of , They all returned to one id, Pass in clearTimeout and clearInterval Can clear this timing operation .

var id = setTimeout(function() {
	console.log('hello world')
}, 2000)

clearTimeout(id);
 Copy code 

If there is no content in the queue at this time , Then Reggie will execute this callback function , If there is content in the queue at this time , Will wait for the content execution to complete before executing this function ,( So even if the waiting time is over , It doesn't immediately execute this callback function )

because setInterval The uncertainty of execution time , So most of the time , We will use setTimeout To simulate the

Use setTimeout To simulate the , Push the next event to the event queue after each execution

Location

attribute : juejin.cn/editor/draf… hash: Hash

host: return url The host name and port of

hostname: Host name

port: port

href: Current url

pathname: url Pathname of Such as :/editor/drafts/6908977883482587149

protocol:url agreement http still https

serch: url The query part of query=string

reload: Reload the current page

replace: Replace the current page with a new page After the domain name

Document

Method : Selectors

Selectors are the most important part of the browser related knowledge , Generally, it will be combined with the actual scene .

getElementById,getElementsByClassName,getElementsBytagName As defined by early norms API, There are new ones querySelector querySelectorAll And so on

a key : getElementsByTagName Wait for more than one return node The function return value of a node is not an array , It's a browser A data structure .

Object.prototype.toString.call(document.getElementsByTagName('i')) // [object HTMLCollection]
 Copy code 

Method : Create elements

document.createElement Be able to create a dom Elements , When adding multiple elements , You can splice all of them in memory first yes , we have dom The element is inserted next time .

 
var fruits = ['Apple', 'Orange', 'Banana', 'Melon'];
var fragment = document.createDocumentFragment(); //  Create a virtual node object 
fruits.forEach(fruit => {
  const li = document.createElement('li');
  li.innerHTML = fruit;
  fragment.appendChild(li);
});
document.body.appendChild(fragment);
 Copy code 

attribute

  • title: document.title You can set or return the current ⻚ Face title

  • domain: Show the domain name of the current website

  • url: Links to the current site

  • anchors: Return to all anchors , belt name Attribute a label

  • forms: Return all form Label set

  • images: Return all img Label set

  • links: Return to all belts href Attribute a label

Element

Element Elemental nodeType Are all 1 , Most tags are one Element example

attribute

tagName: Returns the tag name of the current element

Method

  • getAttribute: Get the result of the current node property

  • setAttribute: Set the current node properties

Text type

Text Type contains all plain text content , It doesn't support child nodes , At the same time, her nodeType by 3

History

History Object contains user ( In the browser window ) Visited URL. stay HTML 5 in ,history Also route information with clients relevant .

attribute

length: Return the number of URLs in the history list

Method

back: load history The previous one in the list URL

forward: load history Next... In the list URL

go: load history A specific one in the list ⻚ Noodles

pushState: Replace address bar address , And join in history list , But it doesn't refresh ⻚ Noodles

replaceState: Replace address bar address , Replace the current ⻚ Face on history Records in the list , It doesn't refresh ⻚ Noodles

summary :

  • Globally defined variables can be accessed through window To visit . Use setInterval We need to pay attention to , It's possible that the code is not At the same interval . Use alert etc. API We need to pay attention to ,JS Code can be blocked .
  • location The object needs to be clear about URL Come on , What is the specific value that each type represents .
  • document The objects are mainly connected JS And our DOM Elements . It should be noted that the result of many choices here is array-like Of Class array elements . And the use of createFragment Code snippets and other optimizations , To prevent performance problems caused by multiple browser rearrangements .
  • Element and Text It's two. We often ⻅ And easy to test and easy to use DOM object . Familiar with chang ⻅ Methods and debug The way (console.dir) Secondly, when writing code, we need to make sure that our current method is JS Level of , It's still environmental .
  • history Because it's closely related to front-end routing , We need to be familiar with the new pushState and replaceState Method .

event

We can do it in many ways DOM Element defines an event :

The first way , Directly in dom Add to element , However, this method is generally not recommended , Over coupling the view with the logical part of the code .

<script>
  function showAlert() {
    alert('hello event');
}
</scripts>
<p onclick="showAlert()"> Click to pop up  alert </p>
 Copy code 

The second way , pure JS solve , obtain dom Element by setting its onclick attribute

 
document.getElementsByTagName('p')[0].onclick = function() {
  alert('hello world');
}
//  To cancel an event, you just need to set  onclick  The attribute is  null  that will do  
document.getElementsByTagName('p')[0].onclick = null;
 Copy code 
  • advantage : pure JS Realization , View is decoupled from logic .
  • shortcoming : One dom Only one element can be set onclick event

The third way , pure JS solve ,DOM2 Level specification implements the new API, addEventListener and removeEventListener Two API

 
var onClickFunc = function() {
  alert('hello world');
};
document.getElementsByTagName('p')[0].addEventListener('click', onClickFunc);
//  Cancel event , Use  removeEventListener  that will do  
document.getElementsByTagName('p')[0].removeEventListener('click', onClickFunc);
 Copy code 
  • advantage :

    1、 pure JS Realization , View is decoupled from logic ;

    2、 adopt addEventListener It can be done to click Set multiple event callback functions , They will trigger in turn

  • shortcoming :

    removeEventListener The deleted event function must maintain the same function reference as it was set , So when setting events Try not to use anonymous functions .

Event capture and bubbling

DOM It's a nested tree structure , The performance in the browser is superimposed , So click on one in the browser Area , stay DOM The structure traverses multiple dom, Top down we call 「 Event capture 」, Bottom up is called 「 event Bubbling 」.

DOM2 The event specification States , A standard event flow is divided into three phases . First of all, top-down 「 Event capture 」 state , And then there was Reach the element that actually triggers the event , Finally, from this element back to the top 「 Event Bubbling 」.

DOM2 Event definition function added by level event specification addEventListener, You can use the third parameter to specify whether you are catching The trigger event in the acquisition phase or the departure event in the bubble phase . The third parameter is zero true It is triggered in the capture phase , The third parameter is zero false It is triggered in the bubbling phase .

IE Medium attachEvent Selection of capture or bubbling stages is not supported , Only supports triggering in bubbling phase .

Event object

After triggering the event , The browser will pass in an event object into the event callback function itself .

document.getElementsByTagName('p')[0].onclick = function(event) {
  console.log(event);
  alert('hello event');
};
document.getElementsByTagName('p')[0].addEventListener('click',
function(event) {
  console.log(event);
})
 Copy code 

event Properties under the object

  • bubbles: Indicates whether the event is bubbling
  • cancelable: Indicates whether the default behavior of an event can be canceled
  • currentTarget: The element that the event is currently processing
  • defaultPrevented: by true It means that
  • preventDefault function detail: Details of the incident
  • eventPhase: The stage of the event ,1 For capture 2 Represents the target in the event 3 For bubbling
  • type: Event type (click etc. )

event Method under object

  • preventDefault: Cancel the default behavior of the event
  • stopImmediatePropagation: Cancels further capture or bubbling of events , It also prevents the event handler from calling
  • stopPropagation: Cancels further capture or bubbling of events

IE Under the object event A little different , If you pass DOM0 Events defined by the specification , It's through window To get event Inside Rong , If it is attachEvent Defining events , It is also passed into the callback function .

var btn = document.getElementById('btn');
// DOM0  Way to define events  btn.onclick = function() {
  var event = window.event;
};
 Copy code 

IE Under the event Property method of

  • cancelBubble: The default is false, Set to true And cancel the event bubble
  • returnValue: The default is true, Set up false Will cancel the default behavior of the event
  • srcElement: The goal of the event
  • type: The type of trigger

Event delegation

<ul id="ul">
    <p>1234</p>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
 
document.getElementById('ul').onclick = function(event) {
  var target = event.target;
  if (target.nodeName.toLowerCase() === 'li') {
    alert(target.innerHTML);
  }
}
 Copy code 

Generic model

The common event model is mainly designed to be compatible with multiple DOM The difference of setting events between levels and IE Different from mainstream norms , At the same time, we need to have both Rong event The content of the event itself .

var addEvent = function(element, eventType, handler) {
  if (element.addEventListener) {
    element.addEventListener(eventType, handler, false);
  } else if (element.attachEvent) {
    element.attachEvent('on' + eventType, handler);
  } else {
    element['on' + eventType] = handler;
  }
}
var removeEvent = function(element, eventType, handler) {
  if (element.removeEventListener) {
    element.removeEventListener(eventType, handler, false);
  } else if (element.detachEvent) {
    element.detachEvent('on' + eventType, handler);
  } else {
    element['on' + eventType] = null;
  }
}
var getTarget = function(event) {
	return event.target || event.srcElement;
}
var preventDefault = function(event) {
  if (event.preventDefault) {
    event.preventDefault();
  } else {
    event.returnValue = false;
  }
}
var stopPropagation = function(event) {
  if (event.stopPropation) {
    event.stopPropation();
  } else {
    event.cancelBubble = true;
  }
}

 Copy code 

版权声明
本文为[You cicada]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152607744M.html

Scroll to Top