信息谷 - ICITU

标题: JavaScript常用代码段 [打印本页]

作者: sxadmin    时间: 2021-10-25 10:31
标题: JavaScript常用代码段
总结一下在各种地方看到的还有自己使用的一些实用代码
1)区分IE和非IE浏览器
if(!+[1,]){     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原生判断是否是移动设备浏览器
[url=][/url]
var mobile=/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i;if(mobile.test(window.navigator.userAgent.toLowerCase())){//是移动设备}else{//不是移动设备}[url=][/url]

17)常用正则表达式
  ①验证是否为负数:/^-\d+$/.test(str)
  ②验证输入是数字:/^\d+$/;
  ③字母.数字和下划线:/^\w+$/;
  ④验证固定电话:/^(\d{3,4})-(\d{7,8})/






欢迎光临 信息谷 - ICITU (https://www.icitu.com/) Powered by Discuz! X3.4