About JavaScript browser objects and javascript

Source: Internet
Author: User

About JavaScript browser objects and javascript

Window

The window object not only acts as a global scope, but also represents a browser window.

The window object has the innerWidth and innerHeight attributes to obtain the internal width and height of the browser window. The internal width and height are used to display the net width and height of a webpage after the placeholder elements such as the menu bar, toolbar, and border are removed. There is also an outerWidth and outerHeight attribute to obtain the entire width and height of the browser window.

Supplement:

Visible area width: document. body. clientWidth: the visible area of the webpage is high: document. body. visible area width of clientHeight webpage: document. body. offsetWidth (including the width of the edge and scroll bar) visible area height of the webpage: document. body. offsetHeight (including the edge width): document. body. scrollWidth: The full text of the webpage is high: document. body. scrollHeight the height of the webpage to be rolled: document. body. scrollTop or jQuery (document ). the left of the scrollTop () webpage to which the volume is redirected: document. body. scrollLeft: window. screenTop page text part left: window. screenLeft screen resolution Height: window. screen. height the screen resolution width: window. screen. width: available workspace height of the screen: window. screen. availHeight available workspace width: window. screen. availWidth screen color bits: window. screen. colorDepth screen pixel/inch ratio: window. screen. the height of the deviceXDPI browser window: $ (window ). height () browser window width: $ (window ). width ()
Special 1: Solution for document. body. scrollTop is always 0 var scrollPos; if (typeof window. pageYOffset! = 'Undefined') {scrollPos = window. pageYOffset;} else if (typeof document. compatMode! = 'Undefined' & document. compatMode! = 'Background') {scrollPos = document.doc umentElement. scrollTop;} else if (typeof document. body! = 'Undefined') {scrollPos = document. body. scrollTop;} alert (scrollPos); Special 2: webpage body full text width: "+ document. body. scrollWidth; full text height of the webpage: "+ document. body. scrollHeight; if the preceding functions cannot be obtained, use the following method. Var xScroll, yScroll; if (window. innerHeight & window. scrollMaxY) {xScroll = document. body. scrollWidth; yScroll = window. innerHeight + window. scrollMaxY;} else if (document. body. scrollHeight> document. body. offsetHeight) {// all but Explorer Mac xScroll = document. body. scrollWidth; yScroll = document. body. scrollHeight;} else {// Explorer Mac... wocould also work in Explorer 6 Strict, Mozilla and Safari xScroll = document. body. offsetWidth; yScroll = document. body. offsetHeight ;}

Navigator

The navigator object indicates the information of the browser. The most common attributes include:

• Navigator. appName: browser name;

• Navigator. appVersion: browser version;

• Navigator. language: The language set by the browser;

• Navigator. platform: operating system type;

• Navigator. userAgent: the User-Agent string set by the browser.

To write different code for different browsers, beginners prefer to use if to determine the browser version. For example:

var width;if (getIEVersion(navigator.userAgent) < 9) {  width = document.body.clientWidth;} else {  width = window.innerWidth;}

However, it may be inaccurate and difficult to maintain the code. The correct method is to make full use of JavaScript to return non-existent attributes.undefinedUsing Short-circuit operators.||Computing:

var width = window.innerWidth || document.body.clientWidth;

Screen

The screen Object indicates the screen information. common attributes include:

• Screen. width: the screen width, in pixels;

• Screen. height: the screen height, in pixels;

• Screen. colorDepth: returns the number of digits of the color, such as 8, 16, and 24.

Location

The location object indicates the URL Information of the current page. For example, a complete URL:

http://www.example.com:8080/path/index.html?a=1&b=2#TOP

Availablelocation.href. To obtain the values of each part of the URL, write as follows:

location.protocol; // 'http'location.host; // 'www.example.com' location.port; // '8080'location.pathname; // '/path/index.html'location.search; // '?a=1&b=2'location.hash; // 'TOP'

To load a new page, you can call location. assign (). To reload the current page, it is very convenient to call the location. reload () method.

Document

The document Object indicates the current page. Because HTML is represented as a tree structure in the form of DOM in the browser, the document object is the root node of the entire DOM tree.

The document title attribute is read from <title> xxx </title> in the HTML document, but can be dynamically changed:

The document Object also has a cookie attribute to obtain the Cookie of the current page.

Cookie is the key-value identifier sent by the server. Because the HTTP protocol is stateless, the server can use cookies to identify which user sends the request. After a user successfully logs on, the server sends a Cookie to the browser, for example, user = ABC123XYZ (encrypted string )..., after that, when the browser accesses the website, the Cookie will be attached to the request header, and the server can distinguish users based on the Cookie.

Cookies can also store website settings, such as the language displayed on the page.

JavaScript can read the cookie of the current page through document. Cookie:

document.cookie; // 'v=123; remember=true; prefer=zh'

Because JavaScript can read the Cookie on the page, and the user's login information is usually contained in the Cookie, this causes a huge security risk, this is because the introduction of third-party JavaScript code to HTML pages is allowed:

<! -- The current page in wwwexample.com --> 

If the introduced third-party JavaScript contains malicious code, the www.foo.com website will directly obtain the user logon information of www.example.com.

To solve this problem, the server can use httpOnly when setting the Cookie. The httpOnly Cookie cannot be read by JavaScript. This behavior is implemented by the browser. Mainstream browsers support the httpOnly option. To ensure security, the server always sticks to httpOnly when setting cookies.

Document. write () only outputs new content to the document

If you execute document. write after the document has been loaded, the entire HTML page will be overwritten:

Reference: http://www.w3school.com.cn/tiy/t.asp? F = js_write_over

DOM | Document

// Return the node with the ID of 'test': var test = document. getElementById ('test'); // obtain all subnodes directly under the test node: var cs = test. children; var first = test. firstElementChild;

The second method is to usequerySelector()AndquerySelectorAll(), You need to understand the selector syntax and then use the conditions to get the node, which is more convenient:

// Obtain the node with ID q1 through querySelector: var q1 = document. querySelector ('# q1'); // use querySelectorAll to obtain all qualified nodes in the q1 node: var ps = q1.querySelectorAll ('div. highlighted> p ');

Strictly speaking, the DOM Node here refers to the Element, but the DOM Node is actually a Node. in HTML, Node includes many types, such as Element, Comment, and CDATA_SECTION, and the root Node Document type. However, in most cases, we only care about the Element, that is, the Node that actually controls the page structure. ignore other types of nodes. The root node Document has been automatically bound to the global variable document.

Modify Dom

Modifying CSS is also a frequently needed operation. The style attribute of the DOM node corresponds to all CSS and can be directly obtained or set. Because CSS allows a name such as font-size, but it is not a valid property name in JavaScript, You need to rewrite it in JavaScript to name fontSize In the hump format:

 

// Obtain <p id = "p-id">... </p> var p = document. getElementById ('P-id'); // sets CSS: p. style. color = '# ff0000'; p. style. fontSize = '20px '; p. style. paddingTop = '2em ';

 Insert DOM

There are two ways to insert a new node. AppendChild is used to add a child node to the last child node of the parent node. For example:

 

<! -- HTML Structure --> <p id = "js"> JavaScript </p> <div id = "list"> <p id = "scheme"> Scheme </p> </div>

Set<p id="js">JavaScript</p>Add<div id="list">The last item:

var js = document.getElementById('js'), list = document.getElementById('list');list.appendChild(js);

Now, the HTML structure is changed to the following:

<! -- HTML Structure --> <div id = "list"> <p id = "scheme"> Scheme </p> <p id = "js"> JavaScript </p> </div>

Because we insertedjsThe node already exists in the current document tree. Therefore, this node will be deleted from the original location and then inserted to the new location.

In more cases, we will create a new node from scratch and insert it to the specified position:

haskell = document.createElement('p');

You can create a node and add it to the DOM tree dynamically to achieve many functions. For example, the following code dynamically creates<style>Node, and then add itAt the end of the node, a new CSS definition is added to the document dynamically:

var d = document.createElement('style');d.setAttribute('type', 'text/css');d.innerHTML = 'p { color: red }';document.getElementsByTagName('head')[0].appendChild(d); 

InsertBefore

What if we want to insert the child node to the specified position? You can use parentElement. insertBefore (newElement, referenceElement); The subnode is inserted before referenceElement.

In many cases, you need to cycle all the child nodes of a parent node, which can be implemented through iteration of the children attribute:

Var I, c, list = document. getElementById ('LIST'); for (I = 0; I <list. children. length; I ++) {c = list. children [I]; // obtain the I subnode}

Delete DOM

To delete a node, first obtain the node itself and its parent node, and then call removeChild of the parent node to delete itself:

// Get the node to be deleted: var self = document. getElementById ('to-be-removed'); // obtain the parent node: var parent = self. parentElement; // Delete: var removed = parent. removeChild (self); removed = self; // true

Note that although the deleted node is not in the document tree, it is still in memory and can be added to another location at any time.

When you traverse and delete a child node of a parent node, note that the children attribute is a read-only attribute and is updated in real time when the child node changes. Therefore, when deleting multiple nodes, note that the children attribute is changing at all times.

Operation form

Using JavaScript to operate a form is similar to operating a DOM, because the form itself is also a DOM tree.

However, the input box and drop-down box of a form can receive user input. Therefore, you can use JavaScript to operate the form to obtain user input content or set new content for an input box.

The following controls are used to input HTML forms:

• Text box, corresponding <input type = "text">, used to input text;

• Password box, corresponding <input type = "password">, used to enter the password;

• Single sequence, corresponding <input type = "radio">, used to select an item;

• Check box, corresponding <input type = "checkbox">, used to select multiple items;

• The <select> drop-down box is used to select an item;

• Hide text. The corresponding <input type = "hidden"> is invisible to users, but the hidden text is sent to the server when the form is submitted.

Get value

If we obtain a reference of the <input> node, we can directly call value to obtain the corresponding user input value:

// <Input type = "text" id = "email"> var input = document. getElementById ('email '); input. value; // 'user input value'

This method can be appliedtext,password,hiddenAndselect. However, for single-region and check boxes,valueThe returned attribute is always the preset value of HTML, but what we need to obtain is whether the user has "checked" the option, so we should usecheckedJudgment:

// <Label> <input type = "radio" name = "weekday" id = "Monday" value = "1"> Monday </label> // <label> <input type = "radio" name = "weekday" id = "Tuesday" value = "2"> Tuesday </label> var mon = document. getElementById ('monday'); var tue = document. getElementById ('tuesday'); mon. value; // '1' tue. value; // '2' mon. checked; // true or falsetue. checked; // true or false

Set Value

The set value is similar to the obtained value. For text, password, hidden, and select, you can directly set the value:

// <Input type = "text" id = "email"> var input = document. getElementById ('email '); input. value = 'test @ example.com '; // the content of the text box has been updated.

Set checked to true or false for single-Statement and check boxes.

HTML5 controls

A large number of standard controls are added to HTML5. Commonly Used controls include date, datetime, datetime-local, and color. They all use the <input> label:

<input type="date" value="2015-07-01">

<input type="datetime-local" value="2015-07-01T02:03:04">

<input type="color" value="#ff0000">

Browsers that do not support HTML5 cannot recognize new controls and use them as type = "text" for display. HTML 5-enabled browsers can obtain formatted strings. For example, the input value of the type = "date" type is guaranteed to be a valid YYYY-MM-DD format date, or an empty string.

Submit Form

Finally, JavaScript can process form submission in two ways (AJAX is described in the following section ).

The first method is to submit a form through the submit () method of the <form> element. For example, to respond to a <button> click Event, submit the form in JavaScript code:

<Form id = "test-form"> <input type = "text" name = "test"> <button type = "button" onclick = "doSubmitForm () "> Submit </button> </form> <script> function doSubmitForm () {var form = document. getElementById ('test-form'); // you can modify the input... // submit form: form. submit () ;}</script>

The disadvantage of this method is that it disrupts the normal submission of form by the browser. Default browser click<button type="submit">Or press enter in the last input box. Therefore, the second method is to respond<form>Its ownonsubmitEvent, which is modified when the form is submitted:

<Form id = "test-form" onsubmit = "return checkForm () "> <input type =" text "name =" test "> <button type =" submit "> Submit </button> </form> <script> function checkForm () {var form = document. getElementById ('test-form'); // you can modify the input... // continue to the next step: return true;} </script>

Note:return trueTo tell the browser to continue submitting. Ifreturn falseThe browser will not continue to submit the form. In this case, the corresponding user input is usually incorrect, prompting the user to submit the form after an error message.

Check and modify<input>Make full use<input type="hidden">To transmit data.

For example, many login forms require the user to enter the user name and password. For security reasons, when submitting the form, the plaintext password is not transmitted, but the MD5 of the password. Common JavaScript developers directly modify<input>:

<Form id = "login-form" method = "post" onsubmit = "return checkForm () "> <input type =" text "id =" username "name =" username "> <input type =" password "id =" password "name =" password "> <button type = "submit"> Submit </button> </form> <script> function checkForm () {var pwd = document. getElementById ('Password'); // convert the plaintext entered by the user to MD5: pwd. value = toMD5 (pwd. value); // continue to the next step: return true ;}</script>

It seems that there is no problem with this practice, but when the user enters the password for submission, the display of the password box will suddenly start from a few*Changed to 32*(Because MD5 has 32 characters ).

You can use<input type="hidden">Implementation:

<Form id = "login-form" method = "post" onsubmit = "return checkForm () "> <input type =" text "id =" username "name =" username "> <input type =" password "id =" input-password "> <input type =" hidden "id =" md5-password "name =" password "> <button type =" submit "> Submit </button> </form> <script> function checkForm () {var input_pwd = document. getElementById ('input-password'); var md5_pwd = document. getElementById ('md5-password'); // convert the plaintext entered by the user to md5: md5_pwd.value = toMD5 (input_pwd.value); // proceed to the next step: return true;} </script>

Note that <input> marked name = "password" with id as md5-password, And the <input> with id as input-password does not have the name attribute. Data without the name attribute <input> will not be submitted.

Operation File

In an HTML form, the only control that can upload files is <input type = "file">.

Note: When a form contains <input type = "file">, the form's enctype must be set to multipart/form-data, and the method must be set to post, the browser can correctly encode and send the form data in multipart/form-data format.

For security reasons, the browser only allows users to click <input type = "file"> to select a local file, using JavaScript to assign values to <input type = "file"> has no effect. After you select to upload a file, JavaScript cannot obtain the actual path of the file:

Files to be uploaded:

Generally, the uploaded files are processed by the backend server. JavaScript can check the file extension when submitting the form to prevent users from uploading invalid files:

var f = document.getElementById('test-file-upload');var filename = f.value; // 'C:\fakepath\test.png'if (!filename || !(filename.endsWith('.jpg') || filename.endsWith('.png') || filename.endsWith('.gif'))) {  alert('Can only upload image file.');  return false;}

File API

Because JavaScript has very limited operations on files uploaded by users, especially the file content cannot be read, many webpages requiring file operations have to be implemented using third-party plug-ins such as Flash.

With the popularity of HTML5, the new File API allows JavaScript to Read File Content and obtain more File information.

The File API of HTML5 provides two main objects: File and FileReader, which can obtain File information and read files.

The following example shows how to read the image file selected by the user and preview the image in <div>:

Image preview:

Var fileInput = document. getElementById ('test-image-file'), info = document. getElementById ('test-file-info'), preview = document. getElementById ('test-image-preview'); // listens for the change event: fileInput. addEventListener ('change', function () {// clear the background image: preview. style. backgroundImage = ''; // check whether the file is selected: if (! FileInput. value) {info. innerHTML = 'no selected file'; return;} // get File reference: var file = fileInput. files [0]; // obtain the File information: info. innerHTML = 'file: '+ file. name + '<br>' + 'size:' + file. size + '<br>' + 'modify:' + file. lastModifiedDate; if (file. type! = 'Image/jpeg '& file. type! = 'Image/png '& file. type! = 'Image/gif') {alert ('is not a valid image file! '); Return;} // read the file: var reader = new FileReader (); reader. onload = function (e) {var data = e.tar get. result; // 'data: image/jpeg; base64,/9j/4AAQSk... (base64 encoding )... 'preview. style. backgroundImage = 'url ('+ data +') ';}; // read the file in DataURL format: reader. readAsDataURL (file );});

The code above demonstrates how to read the File content through the HTML5 File API. The file read in the form of DataURL is a string, similar to data: image/jpeg; base64,/9j/4AAQSk... (base64 encoding )..., it is often used to set images. If processing is required on the server side, send the base64 character string to the server and use Base64 to decode the binary content of the original file.

Callback

The code above also demonstrates an important feature of JavaScript, namely the single-thread execution mode. In JavaScript, the browser's JavaScript execution engine always executes JavaScript code in single-threaded mode. That is to say, JavaScript code cannot be executed by more than one thread at a time.

You may ask how to handle multiple tasks for JavaScript executed in single-thread mode?

In JavaScript, multi-task execution is actually asynchronous, such as the above Code:

reader.readAsDataURL(file);

An Asynchronous Operation is initiated to read the file content. Because it is an asynchronous operation, we do not know when the operation ends in JavaScript code. Therefore, we need to set a callback function first:

Reader. onload = function (e) {// This function is automatically called after the file is read :};

After the file is read, the JavaScript engine automatically calls the callback function we set. When the callback function is executed, the file has been read, so we can safely obtain the file content within the callback function.

The above discussion about the JavaScript browser object is all the content shared by the editor. I hope you can give us a reference and support the house of helpers.

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.