On the _javascript techniques of JavaScript browser objects

Source: Internet
Author: User
Tags base64 button type datetime html form md5


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 properties to get the internal width and height of the browser window. Internal width refers to the removal of the menu bar, toolbars, borders and other placeholder elements, used to display the net width and height of the page. There is also a outerwidth and outerheight property that can get the entire width of the browser window.



Add:


Web page visible area width: document.body.clientWidth
Web page visible area high: document.body.clientHeight
Page visible area width: document.body.offsetWidth (including the width of borders and scroll bars)
Web page visible area height: document.body.offsetHeight (including the width of the border)
Web page full text width: document.body.scrollWidth
The full text of the page body is high: document.body.scrollHeight
The web page is scrolled high: document.body.scrollTop or jQuery (document) .scrollTop ()
Web page scrolled left: document.body.scrollLeft
On the body of the page: window.screenTop
Page body part left: window.screenLeft
High screen resolution: window.screen.height
Screen resolution width: window.screen.width
Screen available workspace height: window.screen.availHeight
Screen available workspace width: window.screen.availWidth
Screen color digits: window.screen.colorDepth
Screen pixel / inch ratio: window.screen.deviceXDPI
Browser window height: $ (window) .height ()
Browser window width: $ (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 of the page body: "+ document.body.scrollWidth;
The full text of the page body is high: "+ document.body.scrollHeight;
The above functions sometimes cannot be obtained, 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 browser's information, and the most commonly used properties include:



navigator.appname: Browser name;



navigator.appversion: Browser version;



Navigator.language: The language of the browser setting;



navigator.platform: Operating system type;



navigator.useragent: Browser-Set user-agent string.



To write different code for different browsers, beginners like to use if to judge the browser version, for example:


var width;
if (Getieversion (navigator.useragent) < 9) {
  width = document.body.clientWidth;
} else {
  width = window.innerwidth;
}


However, this may not be accurate, and it is difficult to maintain the code. The correct approach is to make full use of JavaScript for attributes that do not have properties returnedundefinedby the attribute, directly computed using short-circuit operators||:


var width = Window.innerwidth | | Document.body.clientWidth;


Screen



The Screen object represents the information for the screens, and the commonly used properties are:



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 for the current page. For example, a complete URL:


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


Can be used tolocation.hrefobtain. To get the values for each part of the URL, you can write 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 (). Calling the Location.reload () method is convenient if you want to reload the current page.



Document



The Document object represents the current page. Because HTML is represented as a DOM in the browser as a tree structure, the Document object is the root node of the entire DOM tree.



The title property of document is read from <title>xxx</title> in an HTML document, but can be changed dynamically:



The Document object also has a cookie property to get the cookie for the current page.



Cookies are key-value identifiers sent by the server. Because the HTTP protocol is stateless, the server can distinguish between a cookie and a request to distinguish which user sent it. When a user successfully logs on, the server sends a cookie to the browser, such as USER=ABC123XYZ (encrypted string) ..., after which, when the browser accesses the Web site, the cookie is attached to the request header, and the server distinguishes the user by a cookie.



Cookies can also store some settings for a Web site, such as the language that the page displays, and so on.



JavaScript can read cookies to the current page through Document.cookie:


Document.cookie; ' V=123; Remember=true; Prefer=zh '


Because JavaScript can read cookies to the page, and the user's logon information usually exists in a cookie, this poses a huge security risk because JavaScript code that introduces a third party in an HTML page is allowed:


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


If malicious code is present in the introduction of third party JavaScript, the www.foo.com Web site will directly obtain the user login information for the www.example.com site.



To solve this problem, the server can use HttpOnly when setting cookies, and HttpOnly cookies will not be readable by JavaScript. This behavior is implemented by the browser, mainstream browsers support the HttpOnly option, in order to ensure security, the server side in setting cookies, should always adhere to the use of httponly.



document.write () Only outputs new content to the document



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



Reference: Http://www.w3school.com.cn/tiy/t.asp?f=js_write_over



DOM | Document


Returns the node with ID ' Test ':
var test = document.getElementById (' test ');
Gets all the immediate child nodes under node test:
var cs = Test.children;
var-i = Test.firstelementchild;


The second approach is to usequerySelector()andquerySelectorAll(), you need to understand the selector syntax, and then use the conditions to get the node, more convenient:





Get the node with ID Q1 through Queryselector:
var q1 = document.queryselector (' #q1 ');
Obtain all nodes in the Q1 node by Queryselectorall:
var ps = q1.queryselectorall (' div.highlighted > P ');


Strictly speaking, our DOM node here is the element, but the DOM node is actually node, in HTML, node includes many kinds of element, Comment, cdata_section, and the root node document type, but, Most of the time we only care about element, which is the node that actually controls the structure of the page, and other types of node ignore it. 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 of the CSS and can be directly fetched or set. Because CSS allows font-size to be such a name, it is not a JavaScript-valid property name, so it needs to be rewritten in JavaScript for the hump-named FontSize:





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 add a child node to the last child node of the parent node using AppendChild. For example:





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


To<p id="js">JavaScript</p>add to<div id="list">the last item:


var js = document.getElementById (' js '), List = document.getElementById (' list ');
List.appendchild (JS);


Now, the HTML structure has become this:


<!--HTML structure--><div id= "list" >
  <p id= "scheme" >Scheme</p>
  <p id= "JS" > Javascript</p></div>


Because the node we insertedjsalready exists in the current document tree, the node is first removed from its original location and then inserted into the new location.



More often we will create a new node from zero and then insert it into the specified location:


Haskell = document.createelement (' P ');


Creating a node dynamically and then adding it to the DOM tree enables many functions. For example, the following code dynamically creates a node and<style>then adds it tothe end of the 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} ';


InsertBefore



What if we want to insert the node into the specified position? You can use Parentelement.insertbefore (newelement, referenceelement), and child nodes are inserted before referenceelement.



Many times, you need to loop through all of the child nodes of a parent node, which can be implemented by iterating through the Children property:


var
  i, c,
  list = document.getElementById (' list ');
for (i = 0; i < list.children.length; i++) {
  c = list.children[i];//Get the I sub-node
}


Remove Dom



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


Get the node to delete:
var self = document.getElementById (' to-be-removed ');
Get the parent node:
var parent = self.parentelement;
Delete:
var removed = Parent.removechild (self);
removed = = self; True


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



When you traverse a child node of a parent node and perform a delete operation, note that the Children property is a read-only property and is updated in real time when the child nodes change. Therefore, when you delete multiple nodes, be aware that the children properties change at all times.



Manipulating the form



Using JavaScript to manipulate forms and manipulate the DOM is similar because the form itself is also a DOM tree.



However, the form of the input box, Drop-down box, etc. can receive user input, so use JavaScript to manipulate the form, you can get the user input, or to an input box to set new content.



The main types of input controls for HTML forms are as follows:



• text box, corresponding to the <input type= "text", for input text;



• Password box, corresponding to the <input type= "password", for input password;



• Radio box, corresponding to the <input type= "Radio", for the selection of A;



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



• Drop-down box, corresponding to the <SELECT>, for the selection of an item;



• Hidden text, corresponding to the <input type= "hidden", the user is not visible, but the form submission will send hidden text to the server.



Get value



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


<input type= "text" id= "email" >
var input = document.getElementById (' email ');
Input.value; ' User-entered value '


This approach can be applied totext,password,hiddenandselect. However, for the Radio box and check box, thevalueproperty returns the value of the HTML preset, and what we need to get is whether the user is "hooked up", so you 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 false
tue.checked;//True or False


Setting values



Setting values is similar to getting values, and setting value directly for text, password, hidden, and select can:


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


For a radio box and check box, set checked to True or false.



HTML5 Control



HTML5 has added a number of standard controls, often including date, DateTime, datetime-local, color, all of which use <input> tags:


<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 do not recognize new controls, and they are displayed as type= "text." Browsers that support HTML5 will get a formatted string. For example, the value of an input of type type= "Date" will be guaranteed to be a valid YYYY-MM-DD format date, or an empty string.



Submitting a form



Finally, JavaScript can handle the submission of forms in two ways (Ajax is described in later chapters).



The first way is to submit a form through the submit () method of the <form> element, for example, in response to a <button> click event, to 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 ...
  Submit form:
  form.submit ();
} </script>


The disadvantage of this approach is that it disrupts the browser's normal submission to the form.<button type="submit">The browser submits the form by default, or the user presses the ENTER key in the last input box. Therefore, the second way is to respond<form>to its ownonsubmitevents and make modifications 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 ...
  Continue to the next step: return
  true;
}
</script>


Note toreturn truetell the browser to continue with the submission, ifreturn falsethe browser will not continue to submit form, which usually corresponds to the user input error, prompts the user with the wrong message to terminate the Submit form.



When checking and modifying<input>, make full use of<input type="hidden">to pass data.



For example, many login forms want the user to enter a username and password, but security considerations, when submitting the form, do not transmit the plaintext password, but rather the MD5 of the password. Normal 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 ');  The user entered the plaintext into MD5:
  pwd.value = toMD5 (pwd.value);  Continue to the next step: return
  true;
} </script>


This does not seem to be a problem, but when a user enters a password submission, the display of the password box suddenly changes from several to*32*(because MD5 has 32 characters).



To not change the user's input, you can use the<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 ');  The user entered the plaintext into MD5:
  md5_pwd.value = toMD5 (input_pwd.value);  Continue to the next step: return
  true;
} </script>


Note that <input> marked name= "password" with ID Md5-password, while the user-entered <input> with ID of Input-password does not have a name attribute. <input> data without the name attribute will not be submitted.



Manipulating files



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



Note: When a form contains <input type= "file" >, the enctype of the form must be specified as a multipart/form-data,method must be specified as post for the browser to encode correctly and multipart/ Send the form's data in the Form-data format.



For security reasons, the browser only allows users to click <input type= "File" > to select a local file, with JavaScript <input type= "file" > Value assignment is no effect. When a user chooses to upload a file, JavaScript does not get the true path to the file:






File to upload:



Typically, uploaded files are processed by the backend server, and JavaScript can check the file name extension when submitting the form to prevent users from uploading files that are not in an invalid format:


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;
}


The File API



Because the JavaScript to the user uploads the file operation is very limited, especially cannot read the file content, causes many needs to operate the file the webpage to use the Flash such third party plug-in to realize.



With the popularity of HTML5, the new file API allows JavaScript to read the contents of files and obtain more file information.



The HTML5 file API provides file and FileReader two main objects, which allow you to obtain information about files and read files.



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



Picture preview:




var
  fileInput = document.getElementById ('test-image-file'),
  info = document.getElementById ('test-file-info'),
  preview = document.getElementById ('test-image-preview');
  // Listen for change events:
  fileInput.addEventListener ('change', function () {
  // Clear background image:
  preview.style.backgroundImage = ''; // check if the file is selected:
  if (! fileInput.value) {
    info.innerHTML = 'No files selected';
    return;
  } // Get File reference:
  var file = fileInput.files [0]; // Get 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 ('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 as DataURL:
  reader.readAsDataURL (file);
});


The above code demonstrates how to read the contents of a file through HTML5 's file API. The file read in Dataurl is a string, similar to Data:image/jpeg;base64,/9j/4aaqsk ... (base64 encoding) ..., often used to set up images. If you need server-side processing, the string base64 the word Fu Fa to the server and BASE64 decoding can get the original file binary content.



Callback



The above code also demonstrates one of the most important features of JavaScript is single-threaded execution mode. In JavaScript, the browser's JavaScript execution engine always executes in single-threaded mode when executing JavaScript code, that is, no JavaScript code can be executed with more than 1 threads at any one time.



You might ask, single-threaded mode executes JavaScript, how does multitasking work?



In JavaScript, multitasking is actually called asynchronously, such as the code above:


Reader.readasdataurl (file);


An asynchronous operation is initiated to read the contents of the file. Because it's 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 read is complete, this function is called automatically:
};


When the file is read, the JavaScript engine automatically invokes the callback function that we set. When the callback function is executed, the file is read, so we can safely get the contents of the file within the callback function.



This article on the JavaScript browser object is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.


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.