window
The window object not only acts as a global scope, but also represents a browser window.
The window object has innerWidth and innerHeight properties, which can get the inner width and height of the browser window. Internal width and height refer to the net width and height used to display the web page after removing the placeholder elements such as menu bar, toolbar, border, etc. There is also an outerWidth and outerHeight attributes, which can get the entire width and height of the browser window.
Replenish:
The visible area width of the web page: document.body.clientWidth The visible area height of the web page: document.body.clientHeight The visible area width of the web page: document.body.offsetWidth (including the width of the edge and scroll bar) The visible area height of the web page: document.body.offsetHeight (including the width of the edge) The full text width of the web page: document.body.scrollWidth The full text height of the web page: document.body.scrollHeight The height of the web page being rolled out: document.body.scrollTop or jQuery(document).scrollTop() The left side of the web page being rolled out: document.body.scrollLeft On the web page body part: window.screenTop Web page body part: window.screenLeft The screen resolution height: window.screen.height The screen resolution width: window.screen.width The screen available workspace height: window.screen.availHeight The screen available workspace width: window.screen.availWidth The screen color digits: window.screen.colorDepth The screen pixel/inch ratio: window.screen.deviceXDPI The height of the browser window: $(window).height() The width of the browser window: $(window).width()
Special 1: Solution to document.body.scrollTop is always 0 var scrollPos; if (typeof window.pageYOffset != 'undefined') { scrollPos = window.pageYOffset; } else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { scrollPos = document.documentElement.scrollTop; } else if (typeof document.body != 'undefined') { scrollPos = document.body.scrollTop; } alert(scrollPos); Special 2: The full text width of the web page: "+ document.body.scrollWidth; The full text height of the web page: "+ document.body.scrollHeight; The above functions cannot be obtained sometimes, so 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...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; }navigator
The navigator object represents the information of the browser. The most commonly used properties 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.
In order to write different code for different browsers, beginners like to use if to judge browser version, for example:
var width;if (getIEVersion(navigator.userAgent) < 9) { width = document.body.clientWidth;} else { width = window.innerWidth;} But this may be inaccurate in judgment and it is also difficult to maintain the code. The correct way is to make full use of JavaScript's feature of returning undefined for non-existent properties and directly use the short-circuit operator || to calculate:
var width = window.innerWidth || document.body.clientWidth;
screen
The screen object represents the information of the screen. Common properties include:
•screen.width: screen width, in pixels;
•screen.height: screen height, in pixels;
•screen.colorDepth: Returns the number of color digits, such as 8, 16, 24.
location
The location object represents 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
It can be obtained using location.href . To get the values of each part of the URL, you can write it like this:
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(). If you want to reload the current page, it is very convenient to call the location.reload() method.
document
The document object represents the current page. Since HTML is represented as a tree structure in the browser in the form of DOM, the document object is the root node of the entire DOM tree.
The title attribute of the document is read from <title>xxx</title> in the HTML document, but can be changed dynamically:
The document object also has a cookie attribute, which can get the cookies of the current page.
A cookie is a key-value identifier sent by the server. Because the HTTP protocol is stateless, the server can distinguish between which user's request sent by it, and it can be distinguished by cookies. When a user logs in successfully, the server sends a cookie to the browser, such as user=ABC123XYZ (encrypted string). After that, when the browser accesses the website, it will attach this cookie to the request header, and the server can distinguish users based on the cookie.
Cookies can also store some settings of the website, such as the language of the page displayed, etc.
JavaScript can read the cookies on the current page through document.cookie:
document.cookie; // 'v=123; remember=true; prefer=zh'
Since JavaScript can read cookies on the page, and the user's login information usually also exists in cookies, this creates a huge security risk. This is because introducing third-party JavaScript code into HTML pages is allowed:
<!-- The current page is at wwwexample.com --><html> <head> <script src="http://www.foo.com/jquery.js"></script> </head></html>
If malicious code exists in JavaScript of the introduced third-party introduced, the www.foo.com website will directly obtain the user login information of the www.example.com website.
To solve this problem, the server can use httpOnly when setting cookies. Cookies that set httpOnly will not be read by JavaScript. This behavior is implemented by the browser, and mainstream browsers support the httpOnly option. In order to ensure security, the server should always insist on using httpOnly when setting cookies.
document.write() just outputs new content to the document
If document.write is executed 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 ID 'test': var test = document.getElementById('test');// Get all direct child nodes under node test: var cs = test.children; var first = test.firstElementChild; The second method is to use querySelector() and querySelectorAll() . You need to understand the selector syntax and then use conditions to get the node, which is more convenient:
// Get the node with ID q1 through querySelector: var q1 = document.querySelector('#q1');// Get all nodes in the q1 node that meet the conditions through querySelectorAll: var ps = q1.querySelectorAll('div.highlighted > p');Strictly speaking, the DOM node here refers to Element, but the DOM node is actually Node. In HTML, Node includes many kinds of Element, Comment, CDATA_SECTION, etc., as well as the root node Document type. However, most of the time we only care about Element, that is, Node that actually controls the page structure, and ignore other types of Nodes. The root node Document has been automatically bound to a global variable document.
Modify Dom
Modifying CSS is also a common operation. The style attribute of the DOM node corresponds to all CSSs and can be directly retrieved or set. Because CSS allows names like font-size, but it is not a valid property name for JavaScript, it needs to be rewritten to a camel-style name in JavaScript:
// Get <p id="p-id">...</p>var p = document.getElementById('p-id');// Set CSS:p.style.color = '#ff0000';p.style.fontSize = '20px';p.style.paddingTop = '2em';Insert DOM
There are two ways to insert a new node. One is to use appendChild 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>
Add <p id="js">JavaScript</p> to the last item of <div id="list"> :
var js = document.getElementById('js'), list = document.getElementById('list');list.appendChild(js);Now, the HTML structure becomes like this:
<!-- HTML structure--><div id="list"> <p id="scheme">Scheme</p> <p id="js">JavaScript</p></div>
Because the js node we inserted already exists in the current document tree, this node will first be deleted from its original location and then inserted into a new location.
More often than not, we will create a new node from zero and insert it to the specified location:
haskell = document.createElement('p'); Dynamically creating a node and then adding it to the DOM tree can achieve many functions. For example, the following code dynamically creates a <style> node and adds it to the end of <head> node, thus dynamically adding a new CSS definition to the document:
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 child nodes into the specified location? You can use parentElement.insertBefore(newElement, referenceElement); and the child node will be inserted before the referenceElement.
Many times, it is necessary to loop through all children of a parent node, which can be implemented by iterating over the children attribute:
var i, c, list = document.getElementById('list');for (i = 0; i < list.children.length; i++) { c = list.children[i]; // Get the i-th child node}Delete DOM
To delete a node, first you need to obtain the node itself and its parent node, and then call the parent node's removeChild to delete itself:
// Get the node to be deleted: var self = document.getElementById('to-be-removed');// Get the parent node: var parent = self.parentElement;// Delete: var removed = parent.removeChild(self); removed === self; // trueI noticed that although the deleted node is no longer in the document tree, it is actually still in memory and can be added to another location at any time.
When you traverse a child of a parent node and perform a delete operation, be aware that the children attribute is a read-only attribute and it will be updated in real time when the child node changes. Therefore, when deleting multiple nodes, it is important to note that the children attributes are changing all the time.
Operation form
Using JavaScript to manipulate forms is similar to operating DOM, because the form itself is also a DOM tree.
However, the form's input box, drop-down box, etc. can receive user input, so using JavaScript to operate the form can obtain the content entered by the user, or set new content for an input box.
There are mainly the following input controls for HTML forms:
•Text box, the corresponding <input type="text">, is used to enter text;
• Password box, the corresponding <input type="password">, is used to enter passwords;
•Radio box, the corresponding <input type="radio">, is used to select an item;
• Check box, the corresponding <input type="checkbox"> is used to select multiple items;
•The drop-down box, the corresponding <select>, is used to select an item;
•Hidden text, the corresponding <input type="hidden"> is not visible to the user, but the hidden text will be sent to the server when the form is submitted.
Get the value
If we get a reference to a <input> node, we can directly call value to get the corresponding user input value:
// <input type="text" id="email">var input = document.getElementById('email');input.value; // 'Value entered by the user' This method can be applied to text , password , hidden and select . However, for radio and check boxes, value attribute returns always the HTML preset value, and what we need to obtain is actually whether the user has "checked" option, so checked should be used to judge:
// <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 falseSet value
Setting the value is similar to getting the value. For text, password, hidden and select, you can set the value directly:
// <input type="text" id="email">var input = document.getElementById('email');input.value = '[email protected]'; // The content of the text box has been updatedFor radio and checkboxes, set checked to true or false.
HTML5 controls
HTML5 has added a large number of standard controls, commonly used ones include date, datetime, datetime-local, color, etc. They all use the <input> tag:
<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 will display them as type="text". Browsers that support HTML5 will get formatted strings. For example, the value of type="date" input will be guaranteed to be a valid date in YYYY-MM-DD format, or an empty string.
Submit a form
Finally, JavaScript can handle form submission in two ways (AJAX method is introduced in the following chapter).
The first method is to submit a form through the submit() method of the <form> element. For example, in response 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 form's input here... // Submit form: form.submit();}</script> The disadvantage of this method is that it disrupts the browser's normal submission to form. The browser submits the form when clicking <button type="submit"> by default, or the user presses the Enter key in the last input box. Therefore, the second way is to respond to the onsubmit event of <form> itself and make changes when submitting the form:
<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 form's input here... // Continue to the next step: return true;}</script> Note that return true is required to tell the browser to continue submitting. If return false , the browser will not continue submitting the form. This situation usually corresponds to the user's input error, and the user is prompted for error messages and the form is terminated.
When checking and modifying <input> , make full use of <input type="hidden"> to pass data.
For example, many login forms want users to enter usernames and passwords, but, for security reasons, do not transmit plaintext passwords when submitting the form, but MD5 of the password. Ordinary JavaScript developers will 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'); // Change the plaintext entered by the user to MD5: pwd.value = toMD5(pwd.value); // Continue to the next step: return true;}</script> This method seems to be fine, but when the user enters the password to submit, the password box will suddenly display from several * to 32 * (because MD5 has 32 characters).
To not change the user's input, you can use <input type="hidden"> to implement:
<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'); // Change the plaintext entered by the user to MD5: md5_pwd.value = toMD5(input_pwd.value); // Continue to the next step: return true;}</script>Note that the <input> with id of md5-password marked name="password", while the id entered by the user is input-password without the name attribute. Data without name attribute <input> will not be submitted.
Operation files
In HTML forms, the only control that can upload files is <input type="file">.
Note: When a form contains <input type="file">, the enctype of the form must be specified as multipart/form-data, and the method must be specified as post, so that the browser can correctly encode and send the form's data in multipart/form-data format.
For security reasons, the browser only allows users to click <input type="file"> to select local files. Using JavaScript to assign value to <input type="file"> has no effect. When the user chooses to upload a file, JavaScript cannot obtain the real path to the file:
File to be uploaded:
Usually, uploaded files are processed by the backend server. JavaScript can check the file extension when submitting the form to prevent users from uploading files in invalid formats:
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 inability to read file content, many web pages that require operating files have to be implemented using third-party plug-ins such as Flash.
With the popularity of HTML5, the newly added File API allows JavaScript to read file content and obtain more file information.
HTML5's File API provides two main objects: File and FileReader, which can obtain file information and read files.
The following example demonstrates how to read a user-selected image file and preview the image in a <div>:
Image preview:
var fileInput = document.getElementById('test-image-file'), info = document.getElementById('test-file-info'), preview = document.getElementById('test-image-preview'); // Listen to change events: fileInput.addEventListener('change', function () { // Clear background image: preview.style.backgroundImage = ''; // Check whether the file is selected: if (!fileInput.value) { info.innerHTML = 'No file selected'; return; } // Get File reference: var file = fileInput.files[0]; // Get File information: info.innerHTML = 'File: ' + file.name + '<br>' + 'Size: ' + file.size + '<br>' + 'Modified: ' + file.lastModifiedDate; if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') { alert('is not a valid image file!'); return; } // Read file: var reader = new FileReader(); reader.onload = function(e) { var data = e.target.result; // 'data:image/jpeg;base64,/9j/4AAQSk...(base64 encoding).' preview.style.backgroundImage = 'url(' + data + ')'; }; // Read the file in the form of DataURL: reader.readAsDataURL(file);});The above code demonstrates how to read file contents through HTML5's 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 the server-side processing is required, send the characters after the string base64 to the server and decode it with Base64 to get the binary content of the original file.
Callback
The above code also demonstrates an important feature of JavaScript, which is the single-thread execution mode. In JavaScript, the browser's JavaScript execution engine always executes in single-threaded mode when executing JavaScript code, which means that at any time, it is impossible for the JavaScript code to have more than 1 thread being executed at the same time.
You might ask, how to handle multitasking in single-threaded mode?
In JavaScript, multitasking is actually asynchronously called, such as the above code:
reader.readAsDataURL(file);
An asynchronous operation will be initiated to read the file contents. Because it is an asynchronous operation, we don't know when the operation ends in JavaScript code, so we need to set a callback function first:
reader.onload = function(e) { // When the file is read, this function is automatically called:};When the file read is completed, the JavaScript engine will automatically call the callback function we set. When the callback function is executed, the file has been read, so we can safely obtain the file contents inside the callback function.
The above article briefly talks about the JavaScript browser object is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.