31、原生JavaScript判断是否移动设备
functionisMobile(){ if(typeof this._isMobile === 'boolean'){ return this._isMobile; } varscreenWidth = this.getScreenWidth(); varfixViewPortsExperiment = rendererModel.runningExperiments.FixViewport ||rendererModel.runningExperiments.fixviewport; varfixViewPortsExperimentRunning = fixViewPortsExperiment &&(fixViewPortsExperiment.toLowerCase() === "new"); if(!fixViewPortsExperiment){ if(!this.isAppleMobileDevice()){ screenWidth = screenWidth/window.devicePixelRatio; } } varisMobileScreenSize = screenWidth < 600; varisMobileUserAgent = false; this._isMobile = isMobileScreenSize && this.isTouchScreen(); returnthis._isMobile; }
32、原生JavaScript判断是否移动设备访问
function isMobileUserAgent(){ return(/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase())); }
33、原生JavaScript判断是否苹果移动设备访问
function isAppleMobileDevice(){ return(/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase())); }
34、原生JavaScript判断是否安卓移动设备访问
function isAndroidMobileDevice(){ return(/android/i.test(navigator.userAgent.toLowerCase())); }
35、原生JavaScript判断是否Touch屏幕
function isTouchScreen(){ return(('ontouchstart' in window) || window.DocumentTouch && documentinstanceof DocumentTouch); }
36、原生JavaScript判断是否在安卓上的谷歌浏览器
functionisNewChromeOnAndroid(){ if(this.isAndroidMobileDevice()){ varuserAgent = navigator.userAgent.toLowerCase(); if((/chrome/i.test(userAgent))){ var parts = userAgent.split('chrome/'); var fullVersionString = parts[1].split(" ")[0]; var versionString = fullVersionString.split('.')[0]; var version = parseInt(versionString); if(version >= 27){ return true; } } } returnfalse; }
37、原生JavaScript判断是否打开视窗
function isViewportOpen() { return!!document.getElementById('wixMobileViewport'); }
38、原生JavaScript获取移动设备初始化大小
functiongetInitZoom(){ if(!this._initZoom){ varscreenWidth = Math.min(screen.height, screen.width); if(this.isAndroidMobileDevice() &&!this.isNewChromeOnAndroid()){ screenWidth = screenWidth/window.devicePixelRatio; } this._initZoom = screenWidth /document.body.offsetWidth; } returnthis._initZoom; }
39、原生JavaScript获取移动设备最大化大小
functiongetZoom(){ varscreenWidth = (Math.abs(window.orientation) === 90) ? Math.max(screen.height,screen.width) : Math.min(screen.height, screen.width); if(this.isAndroidMobileDevice() &&!this.isNewChromeOnAndroid()){ screenWidth = screenWidth/window.devicePixelRatio; } varFixViewPortsExperiment = rendererModel.runningExperiments.FixViewport ||rendererModel.runningExperiments.fixviewport; varFixViewPortsExperimentRunning = FixViewPortsExperiment &&(FixViewPortsExperiment === "New" || FixViewPortsExperiment ==="new"); if(FixViewPortsExperimentRunning){ return screenWidth / window.innerWidth; }else{ return screenWidth / document.body.offsetWidth; } }
40、原生JavaScript获取移动设备屏幕宽度
functiongetScreenWidth(){ varsmallerSide = Math.min(screen.width, screen.height); varfixViewPortsExperiment = rendererModel.runningExperiments.FixViewport ||rendererModel.runningExperiments.fixviewport; varfixViewPortsExperimentRunning = fixViewPortsExperiment &&(fixViewPortsExperiment.toLowerCase() === "new"); if(fixViewPortsExperiment){ if(this.isAndroidMobileDevice() &&!this.isNewChromeOnAndroid()){ smallerSide = smallerSide/window.devicePixelRatio; } } returnsmallerSide; }
41、原生JavaScript完美判断是否为网址
function IsURL(strUrl) { varregular =/^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i if(regular.test(strUrl)) { returntrue; } else { returnfalse; } }
42、原生JavaScript根据样式名称检索元素对象
functiongetElementsByClassName(name) { var tags= document.getElementsByTagName('*') || document.all; var els =[]; for (vari = 0; i < tags.length; i++) { if(tags[i].className) { var cs = tags[i].className.split(' '); for (var j = 0; j < cs.length; j++) { if (name == cs[j]) { els.push(tags[i]); break } } } } returnels }
43、原生JavaScript判断是否以某个字符串开头
String.prototype.startWith = function (s) { returnthis.indexOf(s) == 0 }
44、原生JavaScript判断是否以某个字符串结束
String.prototype.endWith = function (s) { var d =this.length - s.length; return (d>= 0 && this.lastIndexOf(s) == d) }
45、原生JavaScript返回IE浏览器的版本号
function getIE(){ if(window.ActiveXObject){ var v= navigator.userAgent.match(/MSIE ([^;]+)/)[1]; returnparseFloat(v.substring(0, v.indexOf("."))) } returnfalse }
46、原生JavaScript获取页面高度
function getPageHeight(){ var g =document, a = g.body, f = g.documentElement, d = g.compatMode =="BackCompat" ?a :g.documentElement; returnMath.max(f.scrollHeight, a.scrollHeight, d.clientHeight); }
47、原生JavaScript获取页面scrollLeft
function getPageScrollLeft(){ var a =document; returna.documentElement.scrollLeft || a.body.scrollLeft; }
48、原生JavaScript获取页面可视宽度
function getPageViewWidth(){ var d =document, a = d.compatMode == "BackCompat" ?d.body :d.documentElement; returna.clientWidth; }
49、原生JavaScript获取页面宽度
function getPageWidth(){ var g =document, a = g.body, f = g.documentElement, d = g.compatMode =="BackCompat" ?a :g.documentElement; returnMath.max(f.scrollWidth, a.scrollWidth, d.clientWidth); }
50、原生JavaScript获取页面scrollTop
function getPageScrollTop(){ var a =document; returna.documentElement.scrollTop || a.body.scrollTop; }
51、原生JavaScript获取页面可视高度
function getPageViewHeight() { var d =document, a = d.compatMode == "BackCompat" ?d.body :d.documentElement; returna.clientHeight; }
52、原生JavaScript跨浏览器添加事件
functionaddEvt(oTarget,sEvtType,fnHandle){ if(!oTarget){return;} if(oTarget.addEventListener){ oTarget.addEventListener(sEvtType,fnHandle,false); }elseif(oTarget.attachEvent){ oTarget.attachEvent("on" + sEvtType,fnHandle); }else{ oTarget["on" + sEvtType] = fnHandle; } }
53、原生JavaScript跨浏览器删除事件
functiondelEvt(oTarget,sEvtType,fnHandle){ if(!oTarget){return;} if(oTarget.addEventListener){ oTarget.addEventListener(sEvtType,fnHandle,false); }elseif(oTarget.attachEvent){ oTarget.attachEvent("on" + sEvtType,fnHandle); }else{ oTarget["on" + sEvtType] = fnHandle; } }
54、原生JavaScript去掉url前缀
function removeUrlPrefix(a){ a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/"); while(trim(a).toLowerCase().indexOf("http://")==0){ a=trim(a.replace(/http:\/\//i,"")); } return a; }
55、原生JavaScript随机数时间戳
function uniqueId(){ vara=Math.random,b=parseInt; returnNumber(new Date()).toString()+b(10*a())+b(10*a())+b(10*a()); }
56、原生JavaScript全角半角转换,iCase:0全到半,1半到全,其他不转化
functionchgCase(sStr,iCase){ if(typeofsStr != "string" || sStr.length <= 0 || !(iCase === 0 || iCase ==1)){ return sStr; } vari,oRs=[],iCode; if(iCase){/*半->全*/ for(i=0; i<sStr.length;i+=1){ iCode = sStr.charCodeAt(i); if(iCode == 32){ iCode = 12288; }else if(iCode < 127){ iCode += 65248; } oRs.push(String.fromCharCode(iCode)); } }else{/*全->半*/ for(i=0; i<sStr.length;i+=1){ iCode = sStr.charCodeAt(i); if(iCode == 12288){ iCode = 32; }else if(iCode > 65280 && iCode < 65375){ iCode -= 65248; } oRs.push(String.fromCharCode(iCode)); } } returnoRs.join(""); }
57、原生JavaScript确认是否键盘有效输入值
functioncheckKey(iKey){ if(iKey== 32 || iKey == 229){return true;}/*空格和异常*/ if(iKey>47 && iKey < 58){return true;}/*数字*/ if(iKey>64 && iKey < 91){return true;}/*字母*/ if(iKey>95 && iKey < 108){return true;}/*数字键盘1*/ if(iKey>108 && iKey < 112){return true;}/*数字键盘2*/ if(iKey>185 && iKey < 193){return true;}/*符号1*/ if(iKey>218 && iKey < 223){return true;}/*符号2*/ returnfalse; }
58、原生JavaScript获取网页被卷去的位置
function getScrollXY() { returndocument.body.scrollTop ? { x:document.body.scrollLeft, y:document.body.scrollTop }: { x:document.documentElement.scrollLeft, y:document.documentElement.scrollTop } }
59、原生JavaScript另一种正则日期格式化函数+调用方法
Date.prototype.format = function(format){//author: meizz var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(format)) format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var kin o)if(new RegExp("("+ k +")").test(format)) format =format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); returnformat; } alert(newDate().format("yyyy-MM-dd hh:mm:ss"));
60、原生JavaScript时间个性化输出功能
/* 1、< 60s,显示为“刚刚” 2、>= 1min&& < 60 min, 显示与当前时间差“XX分钟前” 3、>= 60min&& < 1day, 显示与当前时间差“今天 XX:XX” 4、>= 1day&& < 1year, 显示日期“XX月XX日 XX:XX” 5、>=1year, 显示具体日期“XXXX年XX月XX日 XX:XX” */ functiontimeFormat(time){ var date =new Date(time) , curDate= new Date() , year =date.getFullYear() , month =date.getMonth() + 1 , day =date.getDate() , hour =date.getHours() , minute= date.getMinutes() , curYear= curDate.getFullYear() , curHour= curDate.getHours() ,timeStr; if(year< curYear){ timeStr =year +'年'+ month +'月'+ day +'日 '+ hour +':'+ minute; }else{ varpastTime = curDate - date , pastH= pastTime/3600000; if(pastH> curHour){ timeStr= month +'月'+ day +'日 '+ hour +':'+ minute; }elseif(pastH >= 1){ timeStr= '今天 ' + hour +':'+ minute +'分'; }else{ varpastM = curDate.getMinutes() - minute; if(pastM > 1){ timeStr = pastM +'分钟前'; }else{ timeStr = '刚刚'; } } } returntimeStr; }
http://www.jq-school.com/Show.aspx?id=316