This article is the editor’s daily collection of some classic js examples. I would like to share them on the Script Home platform for your reference!
Add events across browsers
1 2 3 4 5 6 7 8 | function addEvent(obj,type,fn){
if (obj.addEventListener){
obj.addEventListener(type,fn,false);
} else if (obj.attachEvent){
obj.attchEvent( 'on' +type,fn);
}
}
|
Copy after login
Cross-browser removal event
1 2 3 4 5 6 7 8 | function removeEvent(obj,type,fn){
if (obj.removeEventListener){
obj.removeEventListener(type,fn,false);
} else if (obj.detachEvent){
obj.detachEvent( 'on' +type,fn);
}
}
|
Copy after login
Cross-browser blocking default behavior
1 2 3 4 5 6 7 8 9 | function preDef(ev){
var e = ev || window.event;
if (e.preventDefault){
e.preventDefault();
} else {
e.returnValue =false;
}
}
|
Copy after login
Get target object across browsers
1 2 3 4 5 6 7 8 | function getTarget(ev){
if (ev.target){
return ev.target;
} else if (window.event.srcElement){
return window.event.srcElement;
}
}
|
Copy after login
Get scroll bar position across browsers
1 2 3 4 5 6 7 | function getSP(){
return {
top: document.documentElement.scrollTop || document.body.scrollTop,
left : document.documentElement.scrollLeft || document.body.scrollLeft;
}
}
|
Copy after login
Get the visual window size across browsers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function getWindow () {
if (typeof window.innerWidth != 'undefined' ) {
return {
width : window.innerWidth,
height : window.innerHeight
}
} else {
return {
width : document.documentElement.clientWidth,
height : document.documentElement.clientHeight
}
}
},
|
Copy after login
js object impersonation
1 2 3 4 5 6 7 8 9 10 11 12 | <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() ;
Person.call(o , "zhangsan" , 20) ;
console.log(o.say() );
</script>
|
Copy after login
js asynchronous loading and synchronous loading
Asynchronous loading is also called non-blocking mode loading. While the browser is downloading js, it will also perform subsequent page processing.
In the script tag, use js to create a script element and insert it into the document. This is to load the js file asynchronously:
1 2 3 4 5 6 7 8 | ( 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);
})();
|
Copy after login
Synchronized loading
Normally, synchronous loading is used by default. Such as:
1 | <script src= "http://yourdomain.com/script.js" ></script>
|
Copy after login
Synchronous mode, also known as blocking mode, will prevent the browser from subsequent processing. Stops subsequent file parsing and execution, such as image rendering. The reason why the browser adopts the synchronous mode is because the loaded js file has default behaviors such as operating the dom, redirecting, and outputting the document, so synchronization is the safest.
Usually the js to be loaded is placed before the end tag of the body, so that the js can be loaded at the end of the page and minimizes blocking the rendering of the page. This will allow the page to be displayed first.
The synchronous loading process is a waterfall model, and the asynchronous loading process is a concurrent model.
js gets screen coordinates
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!DOCTYPE html>
<html xmlns= "http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=gb2312" />
<meta http-equiv= "X-UA-Compatible" content= "IE=EmulateIE7" />
<meta name= "auther" content= "fq" />
<title>获取鼠标坐标</title>
</head>
<body>
<script type= "text/javascript" >
function mousePosition(ev){
if (ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mousePosition(ev);
document.getElementById( 'xxx' ).value = mousePos.x;
document.getElementById( 'yyy' ).value = mousePos.y;
}
document.onmousemove = mouseMove;
</script>
X:<input id= "xxx" type= "text" /> Y:<input id= "yyy" type= "text" />
</body>
</html>
|
Copy after login
Note:
1. The documentElement property returns the root node of the document.
2.scrollTop() is the distance the scroll bar moves downward
3.document.documentElement.scrollTop refers to the vertical coordinate of the scroll bar
4.document.documentElement.clientHeight refers to the height of the visible area of the browser
-------------------------------------------------- ----------------------------------
When the DTD has been declared:
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
|
Copy after login
如果在页面中添加这行标记的话
IE
document.body.clientWidth ==> BODY对象宽度
document.body.clientHeight ==> BODY对象高度
document.documentElement.clientWidth ==> 可见区域宽度
document.documentElement.clientHeight ==> 可见区域高度
Firefox
document.documentElement.scrollHeight ==> 浏览器所有内容高度
document.body.scrollHeight ==> 浏览器所有内容高度
document.documentElement.scrollTop ==> 浏览器滚动部分高度
document.body.scrollTop ==>始终为0
document.documentElement.clientHeight ==>浏览器可视部分高度
document.body.clientHeight ==> 浏览器所有内容高度
Chrome
document.documentElement.scrollHeight ==> 浏览器所有内容高度
document.body.scrollHeight ==> 浏览器所有内容高度
document.documentElement.scrollTop==> 始终为0
document.body.scrollTop==>浏览器滚动部分高度
document.documentElement.clientHeight ==> 浏览器可视部分高度
document.body.clientHeight ==> 浏览器所有内容高度
浏览器所有内容高度即浏览器整个框架的高度,包括滚动条卷去部分+可视部分+底部隐藏部分的高度总和
浏览器滚动部分高度即滚动条卷去部分高度即可视顶端距离整个对象顶端的高度。
综上
1、document.documentElement.scrollTop和document.body.scrollTop始终有一个为0,所以可以用这两个的和来求scrollTop
2、scrollHeight、clientHeight 在DTD已声明的情况下用documentElement,未声明的情况下用body
clientHeight
在IE和FF下,该属性没什么差别,都是指浏览器的可视区域,即除去浏览器的那些工具栏状态栏剩下的页面展示空间的高度。
PageX和clientX
PageX:鼠标在页面上的位置,从页面左上角开始,即是以页面为参考点,不随滑动条移动而变化
clientX:鼠标在页面上可视区域的位置,从浏览器可视区域左上角开始,即是以浏览器滑动条此刻的滑动到的位置为参考点,随滑动条移动 而变化.
可是悲剧的是,PageX只有FF特有,IE则没有这个,所以在IE下使用这个:
PageY=clientY+scrollTop-clientTop;(只讨论Y轴,X轴同理,下同)
scrollTop代表的是被浏览器滑动条滚过的长度
offsetX:IE特有,鼠标相比较于触发事件的元素的位置,以元素盒子模型的内容区域的左上角为参考点,如果有boder`,可能出现负值
只有clientX和screenX 皆大欢喜是W3C标准.其他的,都纠结了.
最给力的是,chrome和safari一条龙通杀!完全支持所有属性

js拖拽效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!doctype html>
<html lang= "zn-CN" >
<head>
<meta http-equiv= "Content-Type" content= "text/html;charset=UTF-8" />
<title></title>
<style type= "text/css" >
#login{
height: 100px;
width: 100px;
border: 1px solid black;
position: relative;
top:200px;
left: 200px;
background: red;
}
</style>
</head>
<body>
<div id= "login" ></div>
<script type= "text/javascript" >
var oDiv = document.getElementById( "login" );
oDiv.onmousedown = function (e){
var e = e || window.event;
var diffX = e.clientX - oDiv.offsetLeft;
var diffY = e.clientY - oDiv.offsetTop;
document.onmousemove = function (e){
var e = e||window.event;
oDiv.style.left = e.clientX - diffX + 'px' ;
oDiv.style.top = e.clientY -diffY + 'px' ;
};
document.onmouseup = function (){
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
</html>
|
Copy after login
offsetTop 返回的是数字,而 style.top 返回的是字符串,除了数字外还带有单位:px。
js获取图片原始大小尺寸
1 2 3 4 5 6 7 8 | var img = $( "#img_id" );
var pic_real_width, pic_real_height;
$( "<img/>" )
.attr( "src" , $(img).attr( "src" ))
.load( function () {
pic_real_width = this.width;
pic_real_height = this.height;
});
|
Copy after login
js循环遍历数组
1 2 3 4 5 6 7 8 9 | <script>
var animals = [ "cat" , 'dog' , 'human' , 'whale' , 'seal' ];
var animalString = "" ;
for ( var i = 0;i<animals.length;i++){
animalString += animals[i] + " " ;
}
alert(animalString);
</script>
|
Copy after login
遍历二维数组
1 2 3 4 5 6 7 8 9 10 | <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++){
for ( var j=0;j<arr[i].length;j++){
document.writeln(arr[i][j]+ " " );
}
document.writeln( "<br/>" );
}
</script>
|
Copy after login
阻止表单重复提交
有两种方法可以解决:一是提交之后,立刻禁用点击按钮;第二种就是提交之后取消后续的表单提交操作。
document.getElementById("btn").disabled = true;//第一次提交后,将按钮禁用
这种方式只能用于通过提交按钮防止重复提交,还可以使用如下方式:
1 2 3 | var flag = false;
if (flag ==true) return ;
flag = true;
|
Copy after login
字符串部分
在字符串中查找子字符串
1 2 3 4 5 6 | <script type= "text/javascript" >
var test = 'Welcome to my blog!' ;
var value = 'blog' ;
var subValue = test.indexOf(value);
console.log(subValue);
</script>
|
Copy after login
Number和Math部分
数字可以是一个直接量,也可以是一个对象,但是Math对象不同,他没有构造函数,并且其所有的属性和方法都是直接通过这个对象来访问的
把十进制转化为一个十六进制值
1 2 | var num = 255;
console.log(num.toString(16));
|
Copy after login
js中,十进制数字以0x开头,八进制数字总是以0开头
随进产生颜色
1 2 3 4 5 6 7 8 | <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>
|
Copy after login
目前,所有浏览器都支持RGB表示法和十六进制表示法,除了IE7,它只支持十六进制表示法
在角度和弧度之间转换
var rad = degrees*(Math.PI/180);
var degrees = rad*(180/Math.PI);
数组部分
创建多维数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <script type= "text/javascript" >
var arrayLength = 3;
var multiArray = new Array(arrayLength);
for ( var i =0;i<multiArray.length;i++){
multiArray[i] = new Array(arrayLength);
}
multiArray[0][0] = 'phone' ;
multiArray[0][1] = 'book' ;
multiArray[0][2] = 'TV' ;
multiArray[1][0] = 2;
multiArray[1][1] = 1;
multiArray[1][2] = 98;
multiArray[2][0] = [ 'java' , 'python' ];
multiArray[2][1] = [ 'js' , 'C++' ];
multiArray[2][2] = [ 'Haskell' , 'php' ];
</script>
|
Copy after login
排序数组
1 2 3 4 5 6 | <script type= "text/javascript" >
var fruits = [ 'banana' , 'apple' , 'orange' , 'strawberry' ];
console.log(fruits.sort());
var num = [32,43,2,5,-23,0,4];
console.log(num.sort());
</script>
|
Copy after login
Array对象的sort方法会按照字母顺序来排序数组元素。对于数字,是按照字符编码的顺序进行排序
1 2 3 4 5 | function compare(a,b){
return a-b;
}
var num = [32,43,2,5,-23,0,4];
console.log(num.sort(compare));
|
Copy after login
Date日期时间部分
js计算时间差
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var date1= new Date ();
var date2= new Date ();
var date3=date2.getTime()-date1.getTime();
var days=Math. floor (date3/(24*3600*1000));
var leave1=date3%(24*3600*1000);
var hours=Math. floor (leave1/(3600*1000));
var leave2=leave1%(3600*1000);
var minutes=Math. floor (leave2/(60*1000));
var leave3=leave2%(60*1000);
var seconds=Math. round (leave3/1000);
console.log( " 相差 " +days+ "天 " +hours+ "小时 " +minutes+ " 分钟" +seconds+ " 秒" );
|
Copy after login
正则部分
js实现千分位分隔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type= "text/javascript" >
function cc(s){
if (/[^0-9\.]/.test(s)) return "invalid value" ;
s=s.replace(/^(\d*)$/, "$1." );
s=(s+ "00" ).replace(/(\d*\.\d\d)\d*/, "$1" );
s=s.replace( "." , "," );
var re=/(\d)(\d{3},)/;
while (re.test(s))
s=s.replace(re, "$1,$2" );
s=s.replace(/,(\d\d)$/, ".$1" );
return "¥" + s.replace(/^\./, "0." )
}
</script>
<input onchange= "this.value=cc(this.value)" />
|
Copy after login
js判断传入参数是否为质数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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;
}
|
Copy after login
js判断字符串出现最多的字符,并统计次数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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;
}
|
Copy after login
以上内容是小编日常收集整理的JavaScript 经典实例,非常具有参考价值,感兴趣的朋友收藏起来吧。