This is the 13th day of my participation in the August More Text Challenge.More challenges in August

\

BOM

  • EACMScript is the heart of JavaScript, but when you use JavaScript on the Web, the BOM is really the heart. A BOM provides a number of objects for accessing browser functionality that is unrelated to any web page content.
  • The core object of the BOM is the Window, which represents an instance of the browser. In the browser, the Window object has a double standard, both as an interface to access the browser window through JavaScript and as an ECMAScript global object.

6.1 Window Position

  1. Gets the position of the window relative to the left and top of the screen, across the browser

    var leftPos = (typeof window.screenLeft === 'number')?window.screenLeft : window.screenX;
    
    var topPos = (typeof window.screenTop === 'number')?window.screenTop : window.screenY
    Copy the code
  2. The window size

    • Browser window size

      • OuterWidth, outerHeight, innerWidth, innerHeight

        • OuterXXX in IE9+, Firefox, and Sfaria returns the size of the window itself. Opera returns the size of the page container.
        • InnerXXX returns the size of the page view area in the container (minus the border width)
        • OuterXXX returns the same value as innerXXX in chrom. All viewport sizes (without subtracting border values)
      • Document. The documentElement. ClientWidth and document. DocumentElement. ClientHeight have preserved the viewport information page.

        // Get the page viewport size
        document.documentElement.clientWidth && document.body.clientWidth
        Copy the code

####6.2 Navigate and Open Windows

The > window.open method can either navigate to a specific URL or open a new browser window. This method takes four arguments window.open() and passes four arguments 1. The URL to load, the window target, a property string, and a Boolean value indicating whether the new page replaces the currently loaded page in the browser history. Js var win = window.open(' HTTPS: //www.baidu.com', 'newWindow', "height:400, width: 400, top: 10; Left: 10, resizable=yes") // a new window object is returned, which is the window of the window - then the resizeTo method can be called to resize the window. If not, the default Settings are used (right click to open a new TAB) - you can use the reference returned by the open method to resize the window, close the window, and so on.Copy the code

6.3 Intermittent call and Timeout Call

  • Js is a single-threaded language, but it allows code to be scheduled to execute at a specific time by setting timeout values, which execute code after a specified time, and intermittent time values, which specify code at specified intervals.

  • The first argument to timeout and intermittent calls is 1. The code to execute 2. Time in milliseconds

    The second argument is a number of milliseconds indicating how long to wait, but the specified code may not execute after that time. Because js

    Is a single-threaded interpreter, so only one piece of code can be executed at a time. To control which code is executed, there is a JS task queue. The tasks are executed in the order they were added to the queue. The second argument to setTimeout()/setInterval tells JS how long to add the current task to the queue. If the queue is empty, the added code is executed immediately; if the queue is not empty, it waits until the previous code has finished executing.

  • If the first argument to timeout/timeout code is a function, then this executes window in non-strict mode and refers to undefined in strict mode

  • Both timeout and intermittent calls return an ID that can be used to cancel an intermittent call at some future point. To cancel an intermittent call that has not yet been executed, pass in the corresponding ID using clearInterval(ID)/clearTimeout(id). Timeout calls are destroyed after execution, while intermittent calls are executed until the page is unloaded.

  • An example of an intermittent call

    var num = 0
    var max = 10
    var intervalId = null
    
    function incrementNumber() {
    	num++
        
        if(num === max) {
    		clearInterval(intervalId)
            alert('done')
        }
    }
    intervald = setInterval(incrementNumber, 500)
    Copy the code
  • This example can also be implemented using timeout calls

var num = 0
var max = 10

function incrementNumber() {
    num++
    
    if(num < max) {
        console.log(num)
        var id = id+num
        setTimeout(incrementNumber, 500)}else {
        alert('done')}}var id1 = setTimeout(incrementNumber, 500)
Copy the code

As you can see, when using a timeout call, there is no need to keep track of the ID of the timeout call because after each code execution, if another timeout call is not set, the call will stop automatically. It is generally considered a best practice to use timeout calls to simulate intermittent calls, and true intermittent calls are rarely used in a development environment because the later intermittent call may start before the previous one ends. Using timeout calls, as in the previous example, can avoid this altogether. Therefore, it is best not to use intermittent calls.

6.4 location object

  • The Location object is one of the most useful BOM objects, providing information about the document loaded in the current window, as well as some navigation capabilities.

    In fact, the Location object is a very special object, because it’s a property of both the Window object and the document object, in other words, Window.location and Document. location refer to the same object. Location resolves the URL into separate fields, allowing developers to access these fragments through different attributes

    • The properties in location are readable and writable, so it’s easy to change the URL with code to request different resources
6.4.1 Position Operation 2
The property name example instructions
hash “#contents” Returns a hash(# followed by zero or more characters) in the URL, or an empty string if the URL does not contain a hash
host “www.bd.com:80” Returns the server name and port number, if any
href “www.bd.com” Returns the full URL of the currently loaded page, as well as the toString() method of the location object
pathname “/wileyd/” Returns the directory or file name in the URL
port “8080” Returns the port number specified in the URL, or an empty string if the URL does not contain a port number
protocol “http:” The protocol used to return the page, usually HTTP: or HTTPS:
search “? q=javascript” The protocol used to return the page, usually HTTP: or HTTPS:
6.4.2 Obtaining the Parameters of a query String
function getQueryStringArgs() {
	var qs = location.search.length > 0 ? location.search.substring(1) : ' '
    var args = {}
    var items = qs.length ? qs.split('&') : []
    var item = null
    var name = null
    var value = null
    for(var i =0; i<items.length; i++) { item = items[i].split("=")
        // Because query strings are usually encoded
        name = decodeURIComponent(item[0])
        value = decodeURIComponent(item[1])
        if(name.length) {
            args[name] = value
		}
    }
    
    return args
}
Copy the code
6.4.3 Position Operation 2
  • Updating the URL with the properties in the table above generates a new record in the browser’s history, so the user navigates to the previous page using the standalone back button. If you don’t want this behavior, you can use the replace method.

    window.location.replace('http: //www.baidu.com')
    Copy the code
    • After using the replace method, the user cannot go back to the previous page, only to the previous page that was not replaced.
  • Reload method

    window.lcoation.reload() // The browser will load the page in the most efficient way possible (possibly from cache)
    window.lcoation.reload(true) // The browser reloads resources from the server
    Copy the code
    • The code after a reload call may or may not execute, depending on factors such as network latency or system resources, so it’s best to place reload() on the last line of your code

6.5 the navigator object

  • Navigator objects have become the de facto standard for identifying client browsers.

    OnLine system platform where the browser resides cookie whether to enable cookieEnabled userAgent character string userAgentCopy the code
    • It is used to detect the type of browser that displays the web page.

6.6 the screen object

  • Screen objects are not often used in real-world programming. Screen objects are basically used only to indicate the capabilities of the client, including display information outside the browser window, such as pixel width and height.

6.7 the history object

  • The history object holds a history of the user’s Internet access from the moment the window was opened. Because history itself is a window property.. For security reasons, the developer cannot know which urls the user has visited, but the list of pages the user has visited can also be used to move backwards and forwards without knowing the actual URL.
  • Using the go method can jump arbitrarily in the historical record of the users, can be backward or forward, this method takes one parameter, backward or forward jump the number of pages of an integer value, negative said jump back (similar to single the browser’s back button) and positive said jump forward (similar to a single browser’s forward button).
  • You can also pass a string to the GO method, at which point the browser jumps to the most recent page in history that contains the string (either forward or backward).
  • If the go method passes nothing, or if the string passed is not included in the history, then the method does nothing, right

7. Client detection

— Need a copy of the client detection code

8. DOM

DOM is an API for HTML and XML documents that represents a hierarchical tree of nodes, allowing developers to add, remove, and modify portions of a page

8.1 the Document type

JavaScript represents a Document as a Document type. In a browser, the Document object is an instance of HTMLDocument(inherited from the Document type), and represents the entire HTML page. And the Document object is an attribute of the Window object, so it can be accessed as a global object.

  • After the entire page is parsed by the browser, the document contains only one child node, the HTML element. Can be achieved by

    Document.documentelement Gets a reference to the object

  • As an example of HTMLDocument, the Document object also has a body attribute that points directly to the element. Because developers use this element a lot, document.body is very common in JS code

    Document.body gets a reference to the body

  • All browsers support document.documentElement and document.body attributes

  • Html5’s new document.head gets a reference to it

8.2 Document Information

  • Document also provides some information for representing the web page

    // Get the document title
    var originTitle = document.title
    // Set the document title
    document.title = "new page title"
    
    // Get the full URL -- read only
    var url = document.url
    
    // Get domain name -- readable and writable
    var domain = document.domain Because of security restrictions, it is not possible to set any value to the domain. You cannot set this property to a domain not included in the URL// Get the url of the source page -- read only
    var referrer = document.referrer
    Copy the code

8.3 Searching for Elements

  • The most common USE of DOM is to take a reference to a particular element or set of elements and then perform a series of operations.

    document.getelementById () takes an element ID value as an argument and returns it if it is found, or if it is notnullIf there are multiple elements in the page with the same ID value, getElementById returns only the element that appears for the first time in the document.document.getelementsByTagName () this method takes an argument, the tag name of the element to retrieve, and returns nodeList containing zero or more elements. In an Html document, this method returns an HtmlCollection object as an HtmlCollection object"Dynamic"Object that is very similar to nodeListCopy the code
  • The three collections of NodeList and HtmlCollection are dynamic. That is, every time the documents change, they get updated

8.4 Obtaining Attributes

  • Each element has one or more features whose purpose is to give additional information about the element or its contents. There are three DOM methods for manipulating features: getAttribute(), setAttribute(), and removeAttribute().

8.5 Creating Elements

  • Create a new element using the document.createElement() method, which takes only one parameter, the tag name of the element to be created.

    var ele = document.createElement('div')

    • Add new attributes to the element

      ele.id = 'divId ele.className='box'

    • Adding these attributes to new elements simply adds information to them. Since the new element has not yet been added to the document tree, setting these attributes does not affect the browser display. To add new elements to the document tree, use appendChild, InsertBefore or replaceChild methods.

    • Once an element is added to the document tree, the browser renders it immediately, and any subsequent changes to the element are reflected in the browser in real time.

8.6 Creating a Text Node

var ele =  document.createElement('div')

ele.className = 'message'
var textNode = document.createTextNode('Hello World')
ele.appendChild(textNode)
document.body.appendChild(ele)
Copy the code

9. The DOM extension

9.1 Selector API

  • Use CSS selectors as references to retrieved elements in a DOM document query.

  • QuerySelector method

  • QuerySelectAll method

  • MatchesSelector method

    • Match Selector(CSS selector), returns true if the calling element matches the selector, false otherwise

      if(document.body.matchesSelector('body.page1')) {
      	// true or false
      }
      Copy the code

9.2 HTML 5 Extends DOM manipulation methods

  • getElementsByClassName

  • ClassList properties

    • When manipulating class names, you need to add, remove, and replace class names using the className attribute. Because className is a string, you must set the value of the entire string each time you modify even just part of the string.

    • Like a list of divs like this

      <div id="d" class='bd user disabled'>....</div>
      Copy the code
    • Add, delete, change, and check class names using classList

      Document.getelementbyid (‘d’).classList gets the following

const d = document.getElementById('d'D.c. lassList.add(value): Adds the given string value to the list. Contains (value): indicates whether the given value exists in the list, and returns if it doestrueOtherwise returnfalseD.c. lasslist.remove (value): Remove the given string from the list D.C. lasslist.toggle (value): Remove the given string if it already exists in the list, otherwise, add itCopy the code

9.3 Focus Management

  • Html5 adds features to help manage DOM focus, starting with the Document.ActiveElement attribute, which always refers to the element in the DOM that currently has focus. Elements get focus by page loading, user input (usually by pressing the TAB key), and by calling the focus method in code.

  • By default, a reference to the Document. activeElement is stored in the Document. activeElement as soon as the document is loaded, and the value of the Document. activeElement is null while the document is loaded

  • Another addition is the document.hasfocus () method, which is used to determine whether a document is in focus

    You can tell if the user is interacting with the page by detecting whether the document is in focus

Summary: Query the document to know which element gets focus, and to determine if the document gets focus.

9.4 Customizing Data Attributes

  • Html5 allows nonstandard attributes to be added to elements, but with a data- prefix to provide elements with information unrelated to rendering or to provide semantic information. These attributes can be added arbitrarily and named as long as they start with data-.

<div id="myDiv" data-appId="12345" data-myname="ccc"></div>

  • After adding a subdomain attribute, the values of the custom attribute can be accessed using the element’s dataset attribute, whose value is an instance of DOMStringMap, which is a mapping set of key-value pairs.
var d = document.getElementById('myDiv')
// Get the value of the custom attribute
var appId = d.dataset.appId
var myName = d.dataset.myname

/ / set the value
d.dataset.appId = 434521
d.dataset.myname = 'ddd'
Copy the code

P303 — Scroll….

10. DOM2 DOM3

10.1 style

  • Any HTML element that supports the style feature has a corresponding style attribute in JS. This style object is an instance of the cssStrileDeclaration and contains all the style information specified by the HTML style feature. Styles that are layered with external or embedded stylesheets are not included. Any CSS properties specified in the Style property will be represented as corresponding properties of the style object. For CSS property names that use a dash, you must convert them to camel case before they can be accessed through JS.

  • Element. Style. style name = value

Example:

var d = document.getElementById('MyDIV')
d.style.backgroundColor= 'red'
d.style.width = '100px'
d.style.height = '100px'

d.style.border = '1px soild #000'
Copy the code
  • The style object is also used to obtain the style specified in the Style property
console.log(d.style.backgroundColor)
Copy the code

####10.2 Element offset

  • The element’s offset includes all the visible space the element takes up on the screen. The visible size of an element is determined by its height and width, including all inner margins, scrollbars, and border sizes (excluding margins). The offset of the element can be obtained using the following four attributes.

    • OffsetHeight: The vertical footprint of an element, in pixels, including the height of the element, the height of the (visible) horizontal scroll bar, the height of the upper and lower borders
    • OffsetWidth: The amount of horizontal space taken up by an element, in pixels. Includes the width of the element, the (visible) width of the vertical scroll bar, the width of the left and right borders.
    • OffsetLeft: The pixel distance between the left outer border of an element and the left inner border of the containing element.
    • OffsetTop: The pixel distance between the top outer border of an element and the top inner border of the containing element
    • OffsetParent: The nearest location element that contains this element
  • You want to know the offset of an element on the page

    Method one:

    function getOffsetSum(ele) {
        var top = 0, left = 0;
        while (ele) {
            top += ele.offsetTop;
            left += ele.offsetLeft;
            ele = ele.offsetParent;
        }
        return {
            top: top,
            left: left
        }
    }
    Copy the code

    Method 2:

    function getOffsetRect(ele) {
        var box = ele.getBoundingClientRect();
        var body = document.body
        var docElem = document.documentElement;
        // Get the scrollTop,scrollLeft of the page.
        var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
        var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
        var clientTop = docElem.clientTop || body.clientTop
        var clientLeft = docElem.clientLeft || body.clientLeft;
        var top = box.top + scrollTop - clientTop
        var left = box.left + scrollLeft - clientLeft;
        return {
            //Math.round is compatible with Firefox
            top: Math.round(top),
            left: Math.round(left)
        }
    }
    Copy the code

10.3 Client size of an element – Visible area

  • The client area size of an element refers to the amount of space occupied by the element’s content and its inner margins — the visible area
  • ClientWidth and clientHeight
    • The clientWidth property is the width of the element’s content area plus the left and right inner margin widths
    • The clientHeight property is the height of the element’s content plus the height of the upper and lower inner margins.
  • The client area is the amount of space inside the element, so the space occupied by the scroll bar is not counted.
  • The offset and client size of the element are read-only.

10.4 Scroll Size

  • ClientHeight /clientWidht represents the visible size of the element
  • The scroll size refers to the size of the element containing the scroll content.
    • ScrollHeight: The total height of the element’s contents without the scroll bar
    • ScrollWidth: The total width of the element’s content without the scroll bar
    • ScrollLeft: The number of pixels hidden to the left of the content area. You can change the scrolling position of the element by setting this familiarity
    • ScrollTop: The number of pixels hidden above the content area. You can change the scrolling position of an element by setting this property

11. The event

Interaction between JavaScript and HTML is achieved through events, which are specific moments of interaction in a document or browser window that can be scheduled with listeners (event handlers) so that the appropriate code can be executed when the event occurs. This model, known in traditional software engineering as the observer pattern, supports loose coupling between the behavior of the page and the appearance of the page.

11. 1 Event Flow

  • Event bubbling: The event starts on a specific element, which is the object that triggers the event, and then propagates up the DOM tree, occurring at each node, until it propagates to the Document object.
  • Event capture: The event starts on the outermost Document object and propagates down the DOM tree to the actual target of the event.
  • DOM event flow: capture —- before execution of target elements – finally bubbling, capture phase does not trigger events, execution of target elements and bubbling phase trigger events

11.2 Event Handlers

The time is some action that the user’s browser itself performs, and the injection onClick, load, and mouseover are all names of the events. Functions that respond to a certain time are called event handlers (or event listeners), and the name of the event handler begins with ON

11.2.1 HTML event handlers
<input type="button" value="click Me" onclick="showMessage()" />
Copy the code
11.2.2 DOM0-level event handlers
  • Assigns a function to an event handler property
<button id="btn">click Me</button>

var btn = document.getElementById('btn')
btn.onclick = function() {
      // This represents a BTN reference
      alert('click Brn')}// Delete the event handler
btn.onclick = null
Copy the code
11.2.2 DOM2-level event handlers
  • “Dom2-level events” defines two methods for specifying and deleting event handlers.
    • AddEventListener () and removeEventListener ().
    • All DOM modules contain these two methods, and they all take three arguments: the name of the time to process, the function as an event handler, and a Boolean value. The final Boolean parameter, if true, means that the event handler is called in the capture phase, and if false, it means that the event handler is called in the bubble phase
    • Event handlers added by addEventListener can only be removed by removeEventListener, passing in the same parameters as those used to add the handler.
<button id="btn">click Me</button>

var btn = document.getElementById('btn')
btn.addEventListener('click'.function() {
    alert(this.id)
}, false)

btn.removeEventListener('click'.function() {	// cannot be removed!!!! Invalid because event handlers are not the same
    alert('hello World')},false)

/ / effective
var btn = document.getElementById('btn')
var handler = function() {
    alert(this.id)
}
btn.addEventListener('click',handler, false)

btn.removeEventListener('click',handler, false); / / effective
Copy the code
11.2.3 Event Objects

When an event on the DOM is triggered, an event object is generated, which contains all the information related to the event.

1. <input type="button" value="click Me" onclick="showMessage(event)"  />
    
2.  <button id="btn">click Me</button>
    var btn = document.getElementById('btn')
    btn.onclick = function(event) {}3.  var btn = document.getElementById('btn')
    var handler = function (event) {
        console.log(event)
    }
    btn.addEventListener('click', handler, false)
Copy the code
  • Properties in the event object
Properties/methods type Read and write instructions
bubbles Boolean read-only Indicates whether the event can bubble
cancelable Boolean read-only Indicates whether the default behavior of the event can be undone
currentTarget Element read-only The element whose event handler is currently processing the event
defaultPrevented Boolean read-only True indicates that the preventDefault method has been called
detail Integer read-only Details related to the event
eventPhase Integer read-only The stages of invoking the event handler are: 1. capture 2. on target 3. bubble
preventDefault Function read-only Cancels the default behavior of time, which can be used if cancelable is true
stopImmediatePropagation Function read-only Cancels further capture or bubbling of events while preventing any event handlers from being called
stopPropagation Function read-only Cancel further capture or bubbling of events, which can be used if bubbles is true
target Element read-only Object of the event
trusted Boolean read-only A value of true means that the event was generated by the browser, and a value of false means that the event was created by the developer through JS
type String read-only The type of event that is fired
  • This, currentTarget, and target contain the same value if the event handler is specified directly to the target element.
11.2.4 Event Type

There are many types of events that can occur in a Web browser, and different event types have different information. “DOM3” specifies the following types of events

The event describe
UI events Triggered when the user interacts with an element on the page
“Event” Triggered when an element gains or loses focus
Mouse events Triggered when the user performs an action on the page with the mouse
Wheel events Triggered when using the mouse wheel
Synthetic events Triggered when a character is entered for the IME(Input method editor)
Change the time Triggered when the underlying DOM structure changes
  • In addition to these types of events, H5 also defines a set of events, and some browsers implement other proprietary events in the DOM and BOM. These proprietary events are typically developer-specific, with no specification, because implementations may be inconsistent across browsers.
11.2.4.1 UI events
  • Load event: fires on the window when the page is fully loaded (including all images, javascript files, CSS files and other external resources), on the frameset when all frames are loaded, on the frameset when images are loadedTrigger on the element.

    Load events can also be triggered on images, whether they are images in the DOM or images of elements in HTML. So you can specify an onload event handler for any image in HTML1. <img src="smile.gif" onload="alert('Image loaded')">
    
    2.  document.getElementById('myImage').addEventListener('load'.(event) = > {
        	console.log(event)
    	})
    Copy the code
  • Unload events: Fired on the Window when the page is completely unloaded and on the frameset when all frames have been unloaded.

    Triggered when a document is completely unloaded, an Unload event occurs whenever the user switches from one page to another, and references are removed when long is used to avoid memory leaks. Because it is triggered after the document is unloaded, the objects that existed after the page loaded do not necessarily exist. Manipulating the DOM and element styles will result in an error.Copy the code
  • Error event: raised on window when js script error occurs, when image cannot be loadedOn the element,

  • Select event: Triggered when the user selects one or more characters in a text box.

  • Resize event: Triggered on the window or frame when it changes in size.

    The resize event is triggered when the browser window is resized to a new width or heightwindowOn the trigger. Different browsers have different mechanisms for when the resize event is triggered, except that Firefox only triggers when the user stops resizing the window, and everything else changes in the browser window1Pixel when the resize event starts. Do not put too much computational code into the event handler. This code is likely to be executed frequently. This causes the browser to become significantly slower.Copy the code
  • Scroll event: triggered when the user scrolls the contents of an element with a scroll bar.

11.2.4.2 Focus Events
  • Using these events and in conjunction with the document.hasfocus () method and the Document.ActiveElement attribute, as in 9.3, you can know where the user is on the page

  • Blur event: Triggered when an element loses focus. This event does not bubble.

  • Focus: Triggered when the element gains focus, does not bubble

  • Focusin: Equivalent to a blur event, but bubbling

  • Focusout: Equivalent to focus, bubbles

  • When the focus moves from one element on the page to another, the following events are triggered in sequence

    focusout – focusin – blur – focus

11.2.4.3 Mouse and Scroll Events
  • Click: the user’s single main mouse button (usually the left mouse button), or press enter to trigger. This means that the onclick event handler can be executed using either a keyboard or a mouse.

  • Dbclick: the user double-clicks the main mouse button (usually the left mouse button)

  • Mousedown: Triggered when the user presses any mouse button. Cannot be triggered by keyboard.

  • Mouseenter: Triggered when the mouse cursor moves inside the element for the first time from outside the element

  • Mouseleave: Triggered when the mouse cursor over an element moves outside the scope of the element. This event does not bubble

  • Mousemove: Trigger repeatedly when the mouse pointer moves inside an element. This event cannot be triggered by the keyboard.

  • Mouseout: Similar to mouseleave, but bubbling

  • Mouseover: Similar to mouseEnter, but bubbling

  • Mouseup: Triggered when the user releases the mouse button. This event cannot be triggered by the keyboard.

  • Mousewheel: mousewheel event. This event tracks the mousewheel.

All elements on the page support mouse events, except mouseEnter and mouseleave. All mouse events bubble up and can be cancelled, and cancelling mouse events affects the default behavior of the browser. The default behavior of undoing the default mouse event also affects other events, because some mouse events are interdependent.

Click events are emitted only if mouseDown and Mouseup events are emitted sequentially on the same element. Similarly, only two click events trigger a DBClick event.

Events are triggered in the following order:

mousedown – mouseup – click – mouse down – mouseup – click – dbclick

Obviously: Both the Click and DBClick events and depend on the firing of other prior events, while mousedown and Mouseup are unaffected by other events.

  • The client area coordinate position of the mouse event

    Mouse events occur at specific locations in the browser viewport, where information is stored in the clientX and clientY properties of the event object.

    These two values represent the horizontal and vertical coordinates of the mouse pointer in the viewport at the time of the event.

    This value does not include how far the page is scrolling, so this position does not represent where the mouse is on the page.

  • The page coordinate position of the mouse event

    The client coordinates tell you where the mouse occurred in the viewport, while the page coordinates tell you where the event occurred on the page through the pageX and pageY properties of the event object. It is not a viewport, but contains the scrolling distance of the page.

    • In the absence of page scrolling, the values of pageX and pageY are equal to the values of Client X and clientY.
  • The screen coordinate position of the mouse event

    When a mouse event occurs, there is not only a position relative to the browser window, but also a position relative to the entire screen, and the sreenX and sreenY properties can be used to determine the coordinates of the mouse pointer relative to the entire screen when the mouse event occurs.

  • The mouse button

    In mouseDown and Mouseup events, when the mouse is pressed, the event object has a button property that indicates which button is pressed or released. Always the main button on the mobile. Button retrieves which mouse button the user clicked.

  • Touch the equipment

The implementation for ios and Android devices is very special because these devices don’t have a mouse. Here are a few things to keep in mind when developing for iPhone and iPod and Safari

  • Dbclick events are not supported. Double-clicking the browser window enlarges the image and there is no way to change it.
  • The mousemove event is triggered by the standalone element. If this action causes the content to change, no more events will occur. If the screen does not change, the mouseDown, mouseup, and Click events occur in sequence. Contingencies that cannot stand alone do not trigger any events. Singleable elements here refer to elements that can produce default actions. Such as links or elements that already have an onclick event handler configured.
11.2.4.4 Keyboard and Text Events

There are three main events that are most commonly used when a user enters text through a text field.

  • Keydown: This event is triggered repeatedly when the user presses any key on the keyboard
  • Keypress: Triggered when the user presses a character key on the keyboard, and repeatedly if held. Pressing ESC will also trigger.
  • Keyup: Triggered when the user releases a key on the keyboard.

When the user presses a character key on the keyboard, the keyDown event is triggered, the KeyPress event is triggered, and the release event is triggered.

When the user presses a non-character key on the keyboard, a KeyDown event is triggered, then a KeyUP event is triggered, and release triggers a KeyUP event.

  • (event

    This event is triggered when the user enters a character in the editable area. The textInput used to replace KeyPress behaves slightly differently. One of the differences is that the KeyPress event can be triggered by any element that can gain focus. But the textInput event can only be triggered in the editable area. The second difference is that the textInput event is only fired when the user presses a key that can enter an actual character. The keyPress event also fires when a key that affects the text is pressed (such as the backspace key)

11.2.4.5 HTML 5 events
  1. Contextmenu event

    That is, how to call up a context object with the single right mouse button, how to determine whether a context menu should be displayed, and how to mask the default context object associated with that operation. To solve this problem, a contextmenu event is presented to indicate that it is appropriate to display the contextmenu

    html:

    <div id="all">
            <p id="a" style="background-color: blue;">aaaa</p>
            <p>cccc</p>
            <p>cccc</p>
        </div>
        <div>
            <ul id="myMenu" style="position: absolute; visibility: hidden; background-color: silver">
                <li><a href="#">Ha ha</a></li>
                <li><a href="#">Ha ha</a></li>
                <li><a href="#">Hey hey</a></li>
            </ul>
     </div>
    Copy the code

    js:

    <script>
        var d = document.getElementById('all')
    	window.addEventListener('load'.() = > {
            d.addEventListener('contextmenu'.(event) = > {
                event.preventDefault()
                var menu = document.getElementById('myMenu')
                menu.style.left = event.clientX + 'px'
                menu.style.top = event.clientY + 'px'
                menu.style.visibility = 'visible'
            })
            document.addEventListener('click'.function(e) {
                document.getElementById('myMenu').style.visibility = 'hidden'
            })
    	})
    </script>
    Copy the code

    Undoes the default behavior of the ContextMenu event to ensure that the browser’s default context object is not displayed, and then uses the values of the clientX and clientY attributes in the Event object to locate the UL element. The final step is to display the custom context object by setting the visibility property to Bisible. In addition, an onclick event handler has been added to document so that the user can hide the menu with a mouse click.

  2. Beforeunload events

    To make it possible for developers to block this operation before the page is unloaded, this event is triggered before the browser unloads the page. You can use it to unmount and continue with the original page.

    window.addEventListener('beforeunload'.(event) = > {
        var message = 'Are you sure you want to leave this page?'
        event.returnValue = message
        return message
    })
    Copy the code
  3. DOMContentLoaded event

    The onload event for a window fires when everything in the page is loaded, but this process can be too cumbersome to load external resources, whereas the DOMContentLoaded event fires once the DOM is fully formed. Regardless of whether images, JS, CSS files, or other resources have been downloaded.

  4. Hashchange events

    HTML5 has added a Hashchange event to notify developers when the parameter list of a URL (and any strings after the # sign in the URL) changes. This event was added because in Ajax applications, developers often use URL parameter lists to store state or navigation information.

    You must add a Hashchange event handler to the Window object. It is then called whenever the URL parameter list changes.

    window.addEventListener('hashchange'.() = > {
        console.log(location.hash)
    })
    Copy the code
11.2.4.6 Mobile Devices

Touch and gesture events

The following events are for touch devices only

The name of the event Events that
touchstart Triggered when a finger touches the screen, even if a phone is already on the screen
touchmove The continuous trigger as the finger slides across the screen, during this event, call preventDefault() to prevent scrolling
touchend Triggered when the finger is removed from the screen

All of the above events bubble up and can be cancelled, and while touch events are not defined in the DOM specification, they exist in a DOM-compliant manner at the time. So the event object for each touch event provides properties that are common in mouse events.

bubbles cancelable view clientX clientY screenX screenY detail altKey...

In addition to the usual DOM properties, touch events contain the following three properties for tracking touches

  1. Touches: An array of Touch objects representing the Touch operations currently being traced
  2. TargetTouchs: An array of Touch objects specific to the time target
  3. ChangeTouches: An array of Touch objects that represent what has changed since the last Touch.
11.2.5 Simulating Events

Events are often triggered by user actions or through other browser functions. But you can also use JS to trigger specific events at any time, just like events created by the browser, that is, they should bubble and bubble. Function and behavior remain the same

You can create an event object on a Document object using the createEvent() method, which takes a parameter, a string, representing the type of event to be created. This string can be one of the following strings

UIEvents: Generic UI events. Both mouse and keyboard events inherit from UI events.

MouseEvents: generic MouseEvents,

MutationEvents: Generic DOM change events.

HTMLEvents: Generic HTML events.

After the event is simulated, the event is triggered, which requires further use of the dispatchEvent method, which is supported by all DOM nodes that support events. When you call the dispatchEvent method, you pass in a parameter that represents the event object to fire the event. Once an event is triggered, it is classified as an “official event” and can therefore bubble up and trigger the execution of the corresponding event handler.

  • Simulated Mouse events

    The mouse object is created by passing in the string “MouseEvents” for createEvent. The returned object has a method named initMouseEvent that specifies information about the mouse event. This method takes 15 parameters, one for each typical property in the mouse event. The meanings of these parameters are as follows.

    Parameter names The parameter types Parameters that
    type string Represents the type of event to fire, for example click
    bubbles boolean Indicates whether the event should bubble. To accurately simulate mouse events, set this parameter to true
    cancelable boolean Indicates whether the event can be cancelled. To accurately simulate mouse events, set this parameter to true
    view Event-related views, this parameter is almost always set to document.defaultView
    detail int Event-related details. This value is typically used only by event handlers, but is usually set to 0
    screenX int The x coordinate of the event relative to the screen
    screenY int The y-coordinate of the event relative to the screen
    clientX int The X coordinate of the event relative to the viewport
    clientY int The y-coordinate of the event relative to the viewport
    ctrlKey boolean Indicates whether the CTRL key was pressed. The default is false
    altKey boolean Indicates whether the CTRL key was pressed. The default is false
    ctrlKey boolean Indicates whether the Altl key is pressed. The default is false
    shiftKey boolean Indicates whether the Shift key was pressed. Default is false
    metaKey boolean Indicates whether the meta(win) key is pressed. The default is false
    button int Indicates which mouse button was pressed. Default is 0
    relatedTarget object Represents the object associated with the event. This parameter is only used when emulating mouseover or mouseout
  var btn = document.getElementById('btn')
  var event = document.createEvent('MouseEvents')
  event.initMouseEvent('click'.true.true.document.defaultView, 0.0.0.0.false.false.false.false.0.null)
  btn.dispatchEvent(event)
Copy the code