sxadmin 发表于 2021-10-25 10:31:18

JavaScript常用代码段

总结一下在各种地方看到的还有自己使用的一些实用代码1)区分IE和非IE浏览器 if(!+){   alert("这是IE浏览器");} else{   alert("这不是IE浏览器"): }
2)将日期直接转换为数值:+new Date();
3)非IE浏览器下奖类数组对象arguments转换为数组:Array.prototype.slice.call(arguments);
4)void操作符(用来计算一个表达式但是不返回值)<a href="javcascript:void(0)">calamus</a>
5)跳转至新页面,并且保证浏览器不会再回退location.replace("http://www.calamus.cn");
6)几秒钟后返回上一页<meta http-equiv="refresh" content="5;url=jvascript:window.history.go(-1);">
7)在打开的子窗口中刷新父窗口window.opener.location.reload();
8)打印页面window.print();
9)alert()文本换行alert("calamus\np");
10)按键检测event.shiftKey;    //检测shiftevent.altKey;      //检测Altevent.ctrlKey;   //检测Ctrl
检测Ctrl+Enter按键if(event.ctrlKey&&event.keyCode==13){    console.log("calamus");}
11)脚本永不出错的方法window.onerror=function(m,f,l){    return true;}
12)字符串和ASCII码之间的转换console.g("a".charCodeAt(0));console.log(String.fromCharCode(75));
13)判断IE版本window.navigation.appVersion;
14)获取屏幕分辨率的宽、高window.screen.height;window.screen.width;
15)获取浏览器插件的数目navigatior.plugins.length;
16)js原生判断是否是移动设备浏览器https://common.cnblogs.com/images/copycode.gif
var mobile=/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i;if(mobile.test(window.navigator.userAgent.toLowerCase())){//是移动设备}else{//不是移动设备}https://common.cnblogs.com/images/copycode.gif

17)常用正则表达式①验证是否为负数:/^-\d+$/.test(str)②验证输入是数字:/^\d+$/;③字母.数字和下划线:/^\w+$/;④验证固定电话:/^(\d{3,4})-(\d{7,8})/
页: [1]
查看完整版本: JavaScript常用代码段