JavaScript Classic examples Daily collection and collation (common Classic) _javascript skills

Source: Internet
Author: User
Tags array length date1 script tag

This article is a small series of daily collection and collation of some JS classic examples, hereby share to the cloud Habitat Community Platform for your reference!

Adding events across browsers

Cross-browser Add event
function addevent (OBJ,TYPE,FN) {
if (obj.addeventlistener) {
Obj.addeventlistener (TYPE,FN, FALSE);
else if (obj.attachevent) {//ie
obj.attchevent (' on ' +type,fn);
}

Cross-browser removal events

Cross-browser removal event
function removeevent (OBJ,TYPE,FN) {
if (obj.removeeventlistener) {
Obj.removeeventlistener (Type,fn,false);
} else if (obj.detachevent) {//compatible IE
obj.detachevent (' on ' +type,fn);
}

Blocking default behavior across browsers

Cross-browser block default behavior
function predef (EV) {
var e = ev | | window.event;
if (e.preventdefault) {
e.preventdefault ();
} else{
e.returnvalue =false
}
}

Get target objects across browsers

Cross-browser Get target object
function gettarget (EV) {
if (ev.target) {//w3c return
ev.target;
} else if (window.event.srcElement) {//ie return
window.event.srcElement;
}

Get scroll bar position across browser

Get the scroll bar position across the browser, SP = = Scroll position
function getsp () {
return{top
: Document.documentElement.scrollTop | | Document.body.scrollTop,
left:document.documentElement.scrollLeft | | document.body.scrollLeft;
}

Get visual window size across browsers

Get visual window size across browsers
function GetWindow () {
if (typeof window.innerwidth!= ' undefined ') {
return{
Width:window.innerWidth,
height:window.innerHeight
}
} else{return
{
width: Document.documentElement.clientWidth,
height:document.documentElement.clientHeight
}}}
,

JS Object posing as

<script type = ' text/javascript ' >
function person (name, age) {
this.name = name;
This.age = age;
This.say = function () {return
' name: ' + this.name + ' age: ' +this.age;
}
var o = new Object ()//Can be simplified to object ()
person.call (o, "Zhangsan");
Console.log (O.say ());//name:zhangsan age:20 
</script>

JS asynchronous loading and synchronous loading

Asynchronous loading is also called non-blocking mode loading, while the browser downloads JS while also performing subsequent page processing.

In the script tag, using JS to create a SCRIPT element and insert into the document, this is the asynchronous loading of JS files:

(function () { 
var s = document.createelement (' script '); 
S.type = ' text/javascript '; 
S.async = true; 
S.SRC = ' http://yourdomain.com/script.js '; 
var x = document.getelementsbytagname (' script ') [0]; 
X.parentnode.insertbefore (S, x); 
}) ();

Synchronous loading

The usual default is to load synchronously. Such as:

<script src= "Http://yourdomain.com/script.js" ></script>

Synchronous mode, also known as blocking mode, blocks subsequent processing of the browser. Stop the subsequent file parsing, execution, such as image rendering. The browser will use synchronous mode, because the load of JS files in the DOM operation, redirection, output document, such as default behavior, so synchronization is the safest.

Usually put the JS to be loaded before the body end tag, so that JS can be loaded at the end of the page, minimizing the blocking page rendering. This allows the page to be displayed first.

The synchronous loading process is the waterfall model, and the asynchronous loading process is the concurrency model.

JS get screen coordinates

 <! DOCTYPE html>  
 

Comments:

The 1.documentElement property returns the root node of the document.
2.scrollTop () The distance to move the scroll bar down
3.document.documentelement.scrolltop refers to the vertical coordinates of the scroll bar.
4.document.documentelement.clientheight refers to the height of the visible area of the browser

--------------------------------------------------------------------------------

In the case where the DTD has been declared:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

If you add this line of markup to the page

Ie

Document.body.clientWidth ==> Body Object width
Document.body.clientHeight ==> Body Object Height
Document.documentElement.clientWidth ==> Visible Area width
Document.documentElement.clientHeight ==> Visible Area height

Firefox

Document.documentElement.scrollHeight ==> Browser All content height
Document.body.scrollHeight ==> Browser All content height
Document.documentElement.scrollTop ==> Browser Scrolling part height
Document.body.scrollTop ==> is always 0
Document.documentElement.clientHeight ==> Browser Visual part height
Document.body.clientHeight ==> Browser All content height

Chrome

Document.documentElement.scrollHeight ==> Browser All content height
Document.body.scrollHeight ==> Browser All content height
Document.documentelement.scrolltop==> is always 0
Document.body.scrolltop==> Browser Scrolling part height
Document.documentElement.clientHeight ==> Browser Visual part height
Document.body.clientHeight ==> Browser All content height

Browser All content height is the height of the entire frame of the browser, including the scroll bar to Part + visual part + bottom hidden part of the height sum

The browser scrolls the height of the scroll bar to the height of the top of the entire object, depending on its height.

In a comprehensive

1, Document.documentElement.scrollTop and Document.body.scrollTop always have a 0, so you can use these two and to seek scrolltop

2, ScrollHeight, clientheight in the case of the DTD has been declared with the documentelement, without declaring the case with the body

ClientHeight

Under IE and FF, this property is no different, refers to the browser's viewable area, that is, remove the browser of those toolbar status bar remaining page display space height.

Pagex and Clientx

Pagex: The location of the mouse on the page, starting from the top left corner of the page, that is, the page as a reference point, does not move with the sliding bar changes

ClientX: The location of the mouse on the visible area of the page, starting at the upper-left corner of the browser's viewable area, which is the point at which the browser slider is sliding to where it is now, and changes as the slider moves.

But the tragedy is, Pagex only FF-specific, IE does not have this, so in IE under the use of this:

Pagey=clienty+scrolltop-clienttop (only the Y axis, x axis, same below)

The scrolltop represents the length of the scroll that was rolled over by the browser slider.

Offsetx:ie-specific, the mouse is compared to the position of the element that triggers the event, with the upper-left corner of the content area of the element box model as the reference point, and if there is a boder ', a negative value may appear

Only Clientx and Screenx are happy to be the standard of the consortium. The rest are tangled.

Most of all, Chrome and Safari! Full support for all properties

JS drag and drop effect

<!doctype html>  

offsettop returns a number, and Style.top returns a string with a unit in addition to the number: px.

JS get picture Original size size

var img = $ ("#img_id"); Get my img elem
var pic_real_width, pic_real_height;
$ (" 
 

JS Loop Traversal Array

<script> 
//Cyclic traversal array 
var animals = ["Cat", ' dog ', ' human ', ' Whale ', ' seal ']; 
var animalstring = ""; 
for (var i = 0;i<animals.length;i++) { 
animalstring + = Animals[i] + ""; 
} 
alert (animalstring); Each item in the output array

Traversing two-dimensional arrays

<script> 
var arr=[[0,0,0,0,0,0],[0,0,1,0,0,0],[0,2,0,3,0,0],[0,0,0,0,0,0]]; 
for (Var i=0;i<arr.length;i++) { 
//traverse each specific value for 
(Var j=0;j<arr[i].length;j++) { 
Document.writeln ( arr[i][j]+ ""); 
} 
Document.writeln ("<br/>"); 
} 
</script>

Block form repeat submission

There are two ways to fix it: once submitted, disable the Click button immediately, and the second is to cancel subsequent form submission after submission.
document.getElementById ("btn"). Disabled = true;//Disable the button after the first commit

This method can only be used to prevent duplicate submissions through the Submit button, and you can use the following methods:

var flag = false;//Set a listener variable
if (flag ==true) return;//Exit event
flag = true;//Indicates that the file was submitted once.

String part

Find a substring in a string

<script type= "Text/javascript" >
var test = ' Welcome to my blog! ';
var value = ' blog ';
var subvalue = Test.indexof (value);
Console.log (Subvalue);//14, index of substrings
</script>

Number and Math section

A number can be a direct amount, or it can be an object, but the math object is different, he has no constructors, and all of its properties and methods are accessed directly from this object.

Converts decimal to a hexadecimal value

var num = 255;
Console.log (num.tostring);//ff

In JS, decimal digits begin with 0x, and octal numbers always start with 0

Generate Color with Feed

<script type= "Text/javascript" >
function Randomval (val) {return
Math.floor (Math.random () * (val + 1));
function Randomcolor () {return
' rgb (' + randomval (255) + ', ' + randomval (255) + ', ' + randomval (255) + ') '; 
   }
</script>

Currently, all browsers support RGB notation and hexadecimal notation, except IE7, which supports only hexadecimal notation

Converting between angles and radians

var rad = degrees* (math.pi/180);

var degrees = rad* (180/MATH.PI);

Array part

To create a multidimensional array

<script type= "Text/javascript" >
var arraylength = 3;//Set Array length
//create array
var MultiArray = new Array ( Arraylength);
for (var i =0;i<multiarray.length;i++) {
Multiarray[i] = new Array (arraylength);
}
Add an item to the first array index
multiarray[0][0] = ' phone ';
Multiarray[0][1] = ' book ';
MULTIARRAY[0][2] = ' TV ';
Second
multiarray[1][0] = 2;
MULTIARRAY[1][1] = 1;
Multiarray[1][2] = n;
Third
multiarray[2][0] = [' java ', ' Python '];
MULTIARRAY[2][1] = [' js ', ' C + + '];
MULTIARRAY[2][2] = [' Haskell ', ' php '];
</script>

Sort array

<script type= "Text/javascript" >
var fruits = [' banana ', ' apple ', ' orange ', ' Strawberry '];
Console.log (Fruits.sort ());//array ["Apple", "banana", "orange", "Strawberry"]
var num = [32,43,2,5,-23,0,4];
Console.log (Num.sort ())//array [ -23, 0, 2, 4, 5]
</script>

The sort method of the array object sorts the array elements in alphabetical order. For numbers, they are sorted in order of character encoding

function Compare (a,b) {return
a-b;
}
var num = [32,43,2,5,-23,0,4];

Date Time part

JS Calculation time Lag

var date1=new Date (); Start time, current time
var date2=new date ();//end time, need to pass in time parameter
var date3=date2.gettime ()-date1.gettime ();
/calculated the difference days
var days=math.floor (date3/(24*3600*1000));
Calculated the number of hours
var leave1=date3% (24*3600*1000); The number of milliseconds remaining after calculating the number of days
var hours=math.floor (leave1/(3600*1000));
Calculation of the difference in minutes
var leave2=leave1% (3600*1000); The number of milliseconds remaining after the calculation of hours
var minutes=math.floor (leave2/(60*1000));
Calculating the difference in seconds of
var leave3=leave2% (60*1000); The number of milliseconds remaining after the count of minutes
var seconds=math.round (leave3/1000);
Console.log ("Difference" +days+ "Days" +hours+ "hours" +minutes+ "minutes" +seconds+ "seconds");

Regular section

JS implementation of the thousand-bit separation

<script type= "Text/javascript" >
function cc (s) {
if (/[^0-9\.] /.test (s)) return "Invalid value";
S=s.replace (/^ (\d*) $/, "$");
S= (s+). Replace (/(\d*\.\d\d) \d*/, "$");
S=s.replace (".", ",");
var re=/(\d) (\d{3},)/;
while (Re.test (s))
S=s.replace (Re, "$1,$2");
S=s.replace (/, (\d\d) $/, ". $");
Return "¥" + s.replace (/^\./, "0.")
}
</script>
<input onchange= "THIS.VALUE=CC (this.value)"/>

JS determines whether the incoming parameter is prime

function fn (input) {
input = parseint (input,10);
return IsPrime (input)? ' Is prime ': ' not prime ';
}
function IsPrime (input) {
if (Input < 2) {return
false;
} else {for
(var i = 2; I <= math.sqrt (input); i++) {
if (input% i = = 0) {return
false
;
}
}} return true;
}

JS Judge String appears the most characters, and statistics times

JS implements a function to determine the characters with the most occurrences of a string, and to count this number of
function Countstr (str) {
var obj = {};
for (var i = 0, L = str.length,k i < l; i++) {
k = Str.charat (i);
if (Obj[k]) {
obj[k]++;
} else{
Obj[k] = 1;
}}
var m = 0,i=null;
For (var k in obj) {
if (Obj[k] > m) {
m = obj[k];
i = k;
}
}
return i + ': ' + M;
}

The above content is a small series of daily collection and collation of JavaScript classic examples, very valuable reference, interested friends to collect it.

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.