Summary of basic BOM knowledge in javascript

Source: Internet
Author: User
This article summarizes the basic BOM knowledge in javascript. It has good reference value. Let's take a look at the following section. 1. What is BOM?

BOM (Browser Object Document) is the Browser Object model.

BOM provides objects that interact with browser windows independently of the content;

Because BOM is mainly used to manage the communication between windows, its core object is window;

BOM consists of a series of related objects, and each object provides many methods and attributes;

BOM lacks standards. The Standardization Organization of JavaScript syntax is ECMA, DOM Standardization Organization is W3C, and BOM was originally part of the Netscape browser standards.

Ii. Learning BOM

We will learn some objects that interact with the browser window, such as window objects that can be moved or adjusted by the browser size, which can be used for navigation location objects and history objects, the navigator and screen objects of browsers, operating systems, and user screens can be obtained. document can be used as the portal to access HTML documents and frames objects of the management framework. Here, we will only introduce some basic knowledge about window objects, including some ECMAscript knowledge. Other objects such as Location, Screen, Navigator, and History are not described in detail ..

3. window object

Window objects are top-level objects in js. All variables and functions defined in the global scope are converted into properties and methods of window objects. window objects can be omitted during calls.

Example:

Open window. open (url, target, param); // url address to be opened // location of the new target window _ blank _ self _ parent (parent Framework) // some settings of the new window of param // return value. The new window's handle closes the window: window. close ();

Iv. BOM fragmentation knowledge (window object)

1. Timer

Delayed execution of setTimeout ([string | function] code, interval );
ClearTimeout ([number] intervalId );

  Script var btn = document. getElementById ("btn"); var timerId = setTimeout (function () {alert ("23333") ;}, 3000); btn. onclick = function () {// before the set time (within 3 seconds), click to cancel the timer clearTimeout (timerId);} script

Scheduled var timerId = setInterval (code, interval );
ClearInterval (timerId); // clear the timer

Countdown case:

Script var btn = document. getElementById ("btn"); var num = 10; var timerId = setInterval (function () {num --; btn. value = "" + num; if (num = 0) {clearInterval (timerId); btn. disabled = false; btn. value = "agree, you can click" ;}}, 1000); script

2. offset Generation Method

OffsetWidth and offsetHeight

Composition of offsetHeight

OffsetHeight = height + padding + border

Same offsetWidth

OffsetHeight and style. height

1. demo. style. height can only obtain intra-row styles; otherwise, the intra-row styles cannot be obtained.

2. style. height is a string (unit: px) and offsetHeight is a value (unit: Unit: None)

3 .. style. height can be set in-row style, but offsetHeight is a read-only attribute and cannot be set

So: demo. style. height gets the actual height/width of an element, and uses. style. height to set the height/width.

OffsetLeft and offsetTop

Composition of offsetLeft

1. To the left/top of the parent element closest to itself (with positioning)

2. If no parent element is located, the body prevails.

3. offsetLeft is the distance from the left side of the border to the left side of the parent padding.

OffsetLeft and style. left

1. style. left can only obtain intra-row styles.

2, offsetLeft read-only, style. left readable and writable

3. offsetLeft is a numeric value, and style. left is a string in pixels.

4. If no position is found, the value obtained by style. left may be invalid.

5. The biggest difference: offsetLeft uses the upper left corner of border as the benchmark, and style. left uses the upper left corner of margin as the benchmark.

Composition of offsetParent

1. returns the parent-level element with the location closest to the object.

2. If no parent element of the current element is located (position is absolute or relative), offsetParent is the body

3. offsetLeft obtains the distance from offsetParent.

Differences from parentNode

ParentNode always points to the nearest parent element of the current element, whether located or not

3. scroll series methods

Height/width of the actual content inside the scrollHeight and scrollWidth objects (excluding border)

ScrollTop and scrollLeft are the distance from top/left to top/left of the visible area.

Onscroll Event Events events triggered by scroll of the scroll bar

Page rolling coordinate var scrollTop = window. pageYoffset | document.doc umentElement. scrollTop | document. body. scrollTop | 0;

4. client Series

ClientX and clientY obtain the position of the mouse in the visible area. clientX = width + padding, clientY = height + padding

The width of the clientLeft border. If a scroll bar exists, it includes the scroll bar.

For example, obtain the size of the visible area of the page.

function client() {  return {   clientWidth: window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth || 0;    clientHeight: window.innerHeight || document.body.clientHeitght || document.documentElement.clientHeight || 0;  }; }

5. Event parameter e

When an event occurs, the system automatically transmits a parameter to the event processing function to provide event-related data. The compatibility check of event parameter e browser is as follows: e = e | window. event

E. pageX and e. pageY

Obtain the cursor position on the page (pageX and pageY are not supported in IE8, window. event is supported to obtain parameter events) pageX = clientX + the distance from the page to scroll out

6. Obtain the calculated Style

W3c standard window. get ComputedStyle (element, null) [attribute] IE browser element. currentStyle [attribute] encapsulate browser compatibility Function

function getStyle(element, attr) { if(window.getComputedStyle) {  return window.getComputedStyle(element, null)[attr]; } else {  return element.currentStyle[attr]; } }

7. Event supplement

Register an event

Performance issues with registration events

Remove event

Event bubbling

Three phases of event capturing

Common attributes of event objects

The DOM notes contain registration events and removal events. Here we will focus on Event objects and common attributes of event objects.

7.1 target and currentTarget

Target is always the clicked element (IE8 and srcElement)

CurrentTarget executes the element of the event processing function

This is always the same as currentTarget.

7.2 event bubbling

When registering an event with addEventListener, the third parameter is false, that is, bubbling.

Benefits of bubbling-event Delegation

Explain from an example

  
 
 
  • I Have 1st li tags.
  • I have 2nd li tags.
  • I have 3rd li tags.
  • I have 4th li tags.
Script var ul = document. getElementById ("ul"); var btn = document. getElementById ("btn"); // delegate the event that should have been registered with li to ul. You only need to register the event for an element. // dynamically created li, the expected results will also be executed ul. addEventListener ("click", test, false); // register the click Event btn. onclick = function () {// You can also click alert var li = document. createElement ("li"); li. innerHTML = "I am the newly inserted li tag"; ul. appendChild (li) ;}; // The function is written outside the Event code registration to Improve the Performance of function test (e) {alert(e.tar get. innerText);} script

When event bubbling affects the implementation of other functions, You Need To prevent bubbling.

E. stopPropagation () IE8 and earlier: event. cancleBubble = true;

Block execution of default Behaviors

E. preventDefault () IE8 and earlier: event. returnValue = false;

Let's take a look at the example of preventing jump to Baidu:

Baidu script var link = document. getElementById ("link"); link. addEventListener ("click", fn, false); function fn (e) {e. preventDefault (); // if return false is used; does not work, if link is used. onclick = function (); return false can block} script

7.3 mouse event parameters

E. type event type, such as click and mouseover

Three phases of an event, one capture phase, two goals phase, and three bubbles phases

E. eventPhase event phase

ShiftKey/ctrlKey/altKey press the mouse and press the combination key

Button to get the mouse button

E. clientX and e. clientY get the position of the mouse in the visible area

In addition, in section 7.2, events are canceled for bubbling and default behaviors are blocked.

8. Regular Expression

Definition:

A regular expression is a logical formula for string operations. It uses predefined characters and combinations of these specific characters to form a "rule string ", this "rule string" is used to express a filtering logic for strings.

Rules:

1 Metacharacter
. Match any single character, except for line breaks
D digit \ D non-digit [0-9] w digit letter underline \ W non [0-9a-zA-Z _] \ s blank \ S non-Blank
\ N line feed
\ T Tab

2 range -- match a character [0-9] [0123] [a-z] [A-Z] match a character

3 | or

4 quantifiers-Modify only one character

A + 1 or more
A? 1 or 0
A * 0 or multiple
A {x} x n
A {x,} should contain at least x
A {x, y} x-y

5. start and end

^ A starts with
A $ ends with

6 () as a whole, that is, grouping

7. Match Chinese Character [\ u4e00-\ u9fa5] 8 parameters

I case-insensitive
G Global match

9 ^ role in [] -- Inverse

10 greedy mode and non-Greedy Mode

Greedy mode by default <. +>
Non-Greedy mode <. +?>

8.1 RegExp

Baidu script // var regularExpression = new RegExp ("\ d"); // The first method is var regularExpression =/\ d /; // var str = "adfj23dald"; console. log (regularExpression. test (str); // test is the matching method, and the result is true script.

8.2 Regular Expression matching

For example, verify the email address.

// Verify email // abc@sohu.com // 11111@qq.com // aaaaa@163.com // abc@sina.com.cn var reg =/^ \ w + @ \ w + \. \ w + (\. \ w + )? $/; Var str = "abc@sina.com.cn"; console. log (reg. test (str ));

8.3 Regular Expression Extraction

Example: Find a number

Var str = "Zhang San: 1000, Li Si: 5000, Wang Wu: 8000. "; Var reg =/\ d +/g; // by default, the first matching result is returned, followed by a g, that is, the global var arr = str. match (reg); console. log (arr );

8.4 replacement of regular expressions

For example, replace all commas with periods (,).

 var str = "abc,efg,123,abc,123,a"; str = str.replace(/,/g,"."); console.log(str);

8.5 regular grouping ()

In a regular expression, enclose the content to be grouped into a group with RegExp. $1 RegExp. $2 and so on.

For example, the result of exchanging the source string "5 = a, 6 = B, 7 = c" is "a = 5, B = 6, c = 7"

var str = "5=a, 6=b, 7=c";str = str.replace(/(\d+)=(\w+)/g, "$2=$1");console.log(str);

9. keyboard event object [B] [/B]

Method

Keydown Press

Keypress

When keyup is lifted

Attribute

KeyCode keyboard code, which only corresponds to the ASCII code of numbers and letters

CharCode corresponds to the ASCII code, which is only valid in keypress (IE9 +)

For example, when switching the mouse focus, use the enter key instead of the tab key.

 
 
  
  
  Script var inputs = document. body. getElementsByTagName ("input"); for (var I = 0, length = inputs. length; I <length; I ++) {var input = inputs [I]; // the keyCode of the Return key is 13 if (input. type = "text") {// press enter to obtain the focus input for the next text box. onkeydown = function (e) {if (e. keyCode = 13) {this. nextElementSibling. focus (); // focus () It triggers the onfocus event }}} script
 

Supplement: Introduction to the instanceof operator in js

Determines whether a variable is an object of a certain type.

 var num = 5; var arr = []; console.log(num instanceof Array);  //false console.log(arr instanceof Array);  //true

For more articles about BOM basic knowledge in javascript, refer to PHP!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.