数段简单趣味的JavaScript代码

来源:互联网 发布:电脑制作漫画软件 编辑:程序博客网 时间:2024/05/19 22:52

1、 区分IE浏览器

if(!+[1,]){//IE11不支持    swal('这是IE浏览器');}else{    swal('这不是IE浏览器');}

2、 将日期直接转换为数值

 +new Date();//结果为对象类型,毫秒数 //输出 var t = +new Date(); alert(t.toString());

3、非浏览器下将数组对象“arguments”转换成数组

Array.prototype.slice.call(arguments);

4、 最简单的选择运算符

var a = 0 || 3;console.log(a);//=后第一个值计算布尔值为真,取第一个值,否则取第二个

5、 单链式运算

var a=10;console.log(a++ -1);

6、 void操作符
void是一种操作符,用来计算一个表达式,但不返回值,void(expression)中expression是计算的JavaScript标准表达式

<a href='javascript:void(0);'>死链接</a>

7、跳转至新页面,并在保证浏览器不会回退
location的replace()方法可以用一个新的文档替换当前文档,并且该方法还会覆盖history对象中的记录

location.replace(url);

8、几秒钟后回退到上一页

<meta http-equiv="refresh" content="3;url=javascript:window.history.go(-1);">

9、再打开的子窗口中刷新父窗口

window.opener.location.reload();

10、验证是否为负数的正则表达式

/^-\d+$/.test(str);

11、javascript打印页面
window.print()属于浏览器内置的API,可直接打印页面

window:print();

12、实现alert的文本换行

alert('asdfasdfasf\npppppp');

13、javascript中的闭包

//此种方法输出5次,结果都为5for(var i=0; i<5; i++){    setTimeout(function(){        console.log(i);    },1000);}//此种方法输出5次,结果为0,1,2,3,4for(var i=0; i<5; i++){    (function(e){        setTimeout(function(){            console.log(e);        },1000);    })(i);}

14、截取屏幕分辨率的宽,高

window.screen.height;//获取屏幕的高window.screen.width;//获取屏幕的宽

15、脚本永不出错的方式

window.onerror=function(m,f,l){    return true;}

16、javascript处理字符与ASCII码之间的转换
CharCodeAt()返回指定位置字符的Unicode编码;fromCharCode()接收一个指定的Unicode值,返回一个字符串

console.log("a".charCodeAt(0));//97console.log(String.fromCharCode(75));//K

17、访问对象属性
访问对象一般存在两种方式,通过“.”或“[]”。一般情况下两种方式等效,但“[]”还可以动态设置属性

var demo={name:'mk'};demo.name;demo['name'];//动态设置属性var get='boo';demo[get];

18、将一个值转换为布尔类型
使用“!”操作符两次,可将一个值转换为布尔类型

!!'demo';//true!!'';//false!!'0';//true!!'1';//true!!{};//true!!true;//true

19、判断浏览器是否支持html5
在html5中,navigator.geolocation可获取设备的当前位置,通过双“!”就可判断是否支持API,即是否支持html5

!!navigator.geolocation;

20、判断IE版本

window.navigator.appVersion

上述代码返回一个字符串,表示所使用浏览器的版本号。可能只包含一个数字,可能波爱护一些其他的信息
21、声明变量的缩略写法和复杂写法

/*复杂写法*/var x;var y;var z=33;/*缩略写法*/var x,y,z=33

缩略写法更会提高JavaScript的性能
22、捕捉ctrl+enter

//event.ctrlKey检测Ctrl键,event.keyCode==13检测Enter键if(event.ctrlKey && event.keyCode==13){    console.log("you pressed the Ctrl+Enter");}

23、获取浏览器插件的数目

navigator.plugins.length

navigator用来检测浏览器的版本,所指出的MIME类型,已安装的外挂程序(plugin)
24、判断操作系统

//用户代理:userAgentvar osType='';windows = (navigator.userAgent.indexOf("Windwos",0)!=-1)?1:0;mac = (navigator.userAgent.toLowerCase().indexOf("mac",0)!=-1)?1:0;linux = (navigator.userAgent.indexOf("Linux",0)!=-1)?1:0;unix = (navigator.userAgent.indexOf("X11",0)!=-1)?1:0;if(windows) osType = "Windwos";else if(mac) osType = "Mac";else if(linux) osType = "Linux";else if(unix) osType = "Unix";console.log(osType);

25、使用原生JavaScript判断是否是移动设备浏览器

var mobileReg = /iphone|ipad|android.*mobile|window.*phone|blackberry.*mobile/i;if((mobileReg.test(window.navigator.userAgent.toLowerCase()))){    alert('移动设备');}else{    alert('非移动设备');}
0 0
原创粉丝点击