Some classic JavaScript examples worth collecting
JavaScript是一种属于网络的脚本语言,已经被广泛用于Web应用开发,常用来为网页添加各式各样的动态功能,本文就来为大家提供一些JavaScript经典实例,希望对大家有一定的帮助。
跨浏览器事件
跨浏览器添加事件
//跨浏览器添加事件 function addEvent(obj,type,fn){ if(obj.addEventListener){ obj.addEventListener(type,fn,false); }else if(obj.attachEvent){//IE obj.attchEvent('on'+type,fn); } }
跨浏览器移除事件
//跨浏览器移除事件 function removeEvent(obj,type,fn){ if(obj.removeEventListener){ obj.removeEventListener(type,fn,false); }else if(obj.detachEvent){//兼容IE obj.detachEvent('on'+type,fn); } }
跨浏览器阻止默认行为
//跨浏览器阻止默认行为 function preDef(ev){ var e = ev || window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue =false; } }
跨浏览器获取目标对象
//跨浏览器获取目标对象 function getTarget(ev){ if(ev.target){//w3c return ev.target; }else if(window.event.srcElement){//IE return window.event.srcElement; } }
跨浏览器获取滚动条位置
//跨浏览器获取滚动条位置,sp == scroll position function getSP(){ return{ top: document.documentElement.scrollTop || document.body.scrollTop, left : document.documentElement.scrollLeft || document.body.scrollLeft; } }
跨浏览器获取可视窗口大小
//跨浏览器获取可视窗口大小 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 对象冒充
<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() ;//可以简化为Object() Person.call(o , "zhangsan" , 20) ; console.log(o.say() );//name : zhangsan age: 20 </script>
js 异步加载和同步加载
异步加载也叫非阻塞模式加载,浏览器在下载js的同时,同时还会执行后续的页面处理。
在script标签内,用js创建一个script元素并插入到document中,这种就是异步加载js文件了:
(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); })();
同步加载
平常默认用的都是同步加载。如:
<script src="http://yourdomain.com/script.js"></script>
同步模式又称阻塞模式,会阻止流览器的后续处理。停止了后续的文件的解析,执行,如图像的渲染。浏览器之所以会采用同步模式,是因为加载的js文件中有对dom的操作,重定向,输出document等默认行为,所以同步才是最安全的。
通常会把要加载的js放到body结束标签之前,使得js可在页面最后加载,尽量减少阻塞页面的渲染。这样可以先让页面显示出来。同步加载流程是瀑布模型,异步加载流程是并发模型。
js获取屏幕坐标
<!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>
注释:
1、documentElement 属性可返回文档的根节点。
2、scrollTop() 为滚动条向下移动的距离
3、document.documentElement.scrollTop 指的是滚动条的垂直坐标
4、document.documentElement.clientHeight 指的是浏览器可见区域高度
DTD已声明的情况下:
如果在页面中添加这行标记的话
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 ==> 浏览器所有内容高度
js拖拽效果
<!doctype html> <html> <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; //window.event兼容IE,当事件发生时有效 var diffX = e.clientX - oDiv.offsetLeft; //获取鼠标点击的位置到所选对象的边框的水平距离 var diffY = e.clientY - oDiv.offsetTop; document.onmousemove = function(e){ //需设为document对象才能作用于整个文档 var e = e||window.event; oDiv.style.left = e.clientX - diffX + 'px'; //style.left表示所选对象的边框到浏览器左侧距离 oDiv.style.top = e.clientY -diffY + 'px'; }; document.onmouseup = function(){ document.onmousemove = null; //清除鼠标释放时的对象移动方法 document.onmouseup = null; } } </script> </body> </html>
offsetTop 返回的是数字,而 style.top 返回的是字符串,除了数字外还带有单位:px。
js获取图片原始大小尺寸
var img = $("#img_id"); // Get my img elem var pic_real_width, pic_real_height; $("<img/>") // Make in memory copy of image to avoid css issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; // Note: $(this).width() will not pic_real_height = this.height; // work for in memory images. });
js循环遍历数组
<script> //循环遍历数组 var animals = ["cat",'dog','human','whale','seal']; var animalString = ""; for(var i = 0;i<animals.length;i++){ animalString += animals[i] + " "; } alert(animalString); //输出数组里的每个项 </script>
遍历二维数组
<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>
阻止表单重复提交
有两种方法可以解决:一是提交之后,立刻禁用点击按钮;第二种就是提交之后取消后续的表单提交操作。
document.getElementById("btn").disabled = true;//第一次提交后,将按钮禁用
这种方式只能用于通过提交按钮防止重复提交,还可以使用如下方式:
var flag = false;//设置一个监听变量 if(flag ==true)return;//退出事件 flag = true;//表示提交过一次了
字符串部分
在字符串中查找子字符串
<script type="text/javascript"> var test = 'Welcome to my blog!'; var value = 'blog'; var subValue = test.indexOf(value); console.log(subValue);//14,子字符串的索引 </script>
Number和Math部分
数字可以是一个直接量,也可以是一个对象,但是Math对象不同,他没有构造函数,并且其所有的属性和方法都是直接通过这个对象来访问的
把十进制转化为一个十六进制值
var num = 255; console.log(num.toString(16));//ff
js中,十进制数字以0x开头,八进制数字总是以0开头
随机产生颜色
<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>
目前,所有浏览器都支持RGB表示法和十六进制表示法,除了IE7,它只支持十六进制表示法
在角度和弧度之间转换
var rad = degrees*(Math.PI/180); var degrees = rad*(180/Math.PI);
数组部分
创建多维数组
<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>
排序数组
<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, 32, 4, 43, 5 ] </script> Array对象的sort方法会按照字母顺序来排序数组元素。对于数字,是按照字符编码的顺序进行排序 function compare(a,b){ return a-b; } var num = [32,43,2,5,-23,0,4]; console.log(num.sort(compare));//Array [ -23, 0, 2, 4, 5, 32, 43 ]
Date日期时间部分
js计算时间差
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+" 秒");
正则部分
js实现千分位分隔
<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)" />
js判断传入参数是否为质数
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判断字符串出现最多的字符,并统计次数
//js实现一个函数,来判断一个字符串出现次数最多的字符,并统计这个次数 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; }
更多JavaScript知识请关注JavaScript视频教程
The above is the detailed content of Some classic JavaScript examples worth collecting. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
