100个直接可以拿来用的JavaScript实用功能代码片段(一)
1、原生JavaScript实现字符串长度截取
1 function cutstr(str, len) { 2 var temp; 3 var icount = 0; 4 var patrn = /[^\x00-\xff]/; 5 var strre = ""; 6 for (var i = 0; i < str.length; i++) { 7 if (icount < len - 1) { 8 temp = str.substr(i, 1); 9 if (patrn.exec(temp) == null) { 10 icount = icount + 1 11 } else { 12 icount = icount + 2 13 } 14 strre += temp 15 } else { 16 break 17 } 18 } 19 return strre + "..." 20 }
2、原生JavaScript获取域名主机
3、原生JavaScript清除空格
1 String.prototype.trim = function() { 2 var reExtraSpace = /^\s*(.*?)\s+$/; 3 return this.replace(reExtraSpace, "$1") 4 }
4、原生JavaScript替换全部
1 String.prototype.replaceAll = function(s1, s2) { 2 return this.replace(new RegExp(s1, "gm"), s2) 3 }
5、原生JavaScript转义html标签
1 function HtmlEncode(text) { 2 return text.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>') 3 }
6、原生JavaScript还原html标签
1 function HtmlDecode(text) { 2 return text.replace(/&/g, '&').replace(/"/g, '\"').replace(/</g, '<').replace(/>/g, '>') 3 }
7、原生JavaScript时间日期格式转换
1 Date.prototype.Format = function(formatStr) { 2 var str = formatStr; 3 var Week = ['日', '一', '二', '三', '四', '五', '六']; 4 str = str.replace(/yyyy|YYYY/, this.getFullYear()); 5 str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100)); 6 str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1)); 7 str = str.replace(/M/g, (this.getMonth() + 1)); 8 str = str.replace(/w|W/g, Week[this.getDay()]); 9 str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate()); 10 str = str.replace(/d|D/g, this.getDate()); 11 str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours()); 12 str = str.replace(/h|H/g, this.getHours()); 13 str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes()); 14 str = str.replace(/m/g, this.getMinutes()); 15 str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds()); 16 str = str.replace(/s|S/g, this.getSeconds()); 17 return str 18 }
8、原生JavaScript判断是否为数字类型
9、原生JavaScript设置cookie值
1 function setCookie(name, value, Hours) { 2 var d = new Date(); 3 var offset = 8; 4 var utc = d.getTime() + (d.getTimezoneOffset() * 60000); 5 var nd = utc + (3600000 * offset); 6 var exp = new Date(nd); 7 exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000); 8 document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;" 9 }
10、原生JavaScript获取cookie值
1 function getCookie(name) { 2 var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); 3 if (arr != null) return unescape(arr[2]); 4 return null 5 }
11、原生JavaScript加入收藏夹
12、原生JavaScript设为首页
1 function setHomepage() { 2 if (document.all) { 3 document.body.style.behavior = 'url(#default#homepage)'; 4 document.body.setHomePage('http://www.jq-school.com') 5 } else if (window.sidebar) { 6 if (window.netscape) { 7 try { 8 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect") 9 } catch(e) { 10 alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true") 11 } 12 } 13 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); 14 prefs.setCharPref('browser.startup.homepage', 'http://www.jq-school.com') 15 } 16 }
13、原生JavaScript判断IE6
14、原生JavaScript加载样式文件
1 function LoadStyle(url) { 2 try { 3 document.createStyleSheet(url) 4 } catch(e) { 5 var cssLink = document.createElement('link'); 6 cssLink.rel = 'stylesheet'; 7 cssLink.type = 'text/css'; 8 cssLink.href = url; 9 var head = document.getElementsByTagName('head')[0]; 10 head.appendChild(cssLink) 11 } 12 }
15、原生JavaScript返回脚本内容
1 function evalscript(s) { 2 if(s.indexOf('<script') == -1) return s; 3 var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig; 4 var arr = []; 5 while(arr = p.exec(s)) { 6 var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i; 7 var arr1 = []; 8 arr1 = p1.exec(arr[0]); 9 if(arr1) { 10 appendscript(arr1[1], '', arr1[2], arr1[3]); 11 } else { 12 p1 = /<script(.*?)>([^\x00]+?)<\/script>/i; 13 arr1 = p1.exec(arr[0]); 14 appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1); 15 } 16 } 17 return s; 18 }
16、原生JavaScript清除脚本内容
1 function stripscript(s) { 2 return s.replace(/<script.*?>.*?<\/script>/ig, ''); 3 }
17、原生JavaScript动态加载脚本文件
1 function appendscript(src, text, reload, charset) { 2 var id = hash(src + text); 3 if(!reload && in_array(id, evalscripts)) return; 4 if(reload && $(id)) { 5 $(id).parentNode.removeChild($(id)); 6 } 7 8 evalscripts.push(id); 9 var scriptNode = document.createElement("script"); 10 scriptNode.type = "text/javascript"; 11 scriptNode.id = id; 12 scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset); 13 try { 14 if(src) { 15 scriptNode.src = src; 16 scriptNode.onloadDone = false; 17 scriptNode.onload = function () { 18 scriptNode.onloadDone = true; 19 JSLOADED[src] = 1; 20 }; 21 scriptNode.onreadystatechange = function () { 22 if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) { 23 scriptNode.onloadDone = true; 24 JSLOADED[src] = 1; 25 } 26 }; 27 } else if(text){ 28 scriptNode.text = text; 29 } 30 document.getElementsByTagName('head')[0].appendChild(scriptNode); 31 } catch(e) {} 32 }
18、原生JavaScript返回按ID检索的元素对象
1 function $(id) { 2 return !id ? null : document.getElementById(id); 3 }
19、原生JavaScript返回浏览器版本内容
1 function browserVersion(types) { 2 var other = 1; 3 for(i in types) { 4 var v = types[i] ? types[i] : i; 5 if(USERAGENT.indexOf(v) != -1) { 6 var re = new RegExp(v + '(\\/|\\s)([\\d\\.]+)', 'ig'); 7 var matches = re.exec(USERAGENT); 8 var ver = matches != null ? matches[2] : 0; 9 other = ver !== 0 && v != 'mozilla' ? 0 : other; 10 }else { 11 var ver = 0; 12 } 13 eval('BROWSER.' + i + '= ver'); 14 } 15 BROWSER.other = other; 16 }
20、原生JavaScript元素显示的通用方法
1 function $(id) { 2 return !id ? null : document.getElementById(id); 3 } 4 function display(id) { 5 var obj = $(id); 6 if(obj.style.visibility) { 7 obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible'; 8 } else { 9 obj.style.display = obj.style.display == '' ? 'none' : ''; 10 } 11 }
21、原生JavaScript中有insertBefore方法,可惜却没有insertAfter方法?用如下函数实现
22、原生JavaScript中兼容浏览器绑定元素事件
23、原生JavaScript光标停在文字的后面,文本框获得焦点时调用
24、原生JavaScript检验URL链接是否有效
1 function getUrlState(URL){ 2 var xmlhttp = new ActiveXObject("microsoft.xmlhttp"); 3 xmlhttp.Open("GET",URL, false); 4 try{ 5 xmlhttp.Send(); 6 }catch(e){ 7 }finally{ 8 var result = xmlhttp.responseText; 9 if(result){ 10 if(xmlhttp.Status==200){ 11 return(true); 12 }else{ 13 return(false); 14 } 15 }else{ 16 return(false); 17 } 18 } 19 }
25、原生JavaScript格式化CSS样式代码
1 function formatCss(s){//格式化代码 2 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); 3 s = s.replace(/;\s*;/g, ";"); //清除连续分号 4 s = s.replace(/\,[\s\.\#\d]*{/g, "{"); 5 s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2"); 6 s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2"); 7 s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2"); 8 return s; 9 }
26、原生JavaScript压缩CSS样式代码
1 function yasuoCss (s) {//压缩代码 2 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释 3 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); 4 s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理 5 s = s.replace(/;\s*;/g, ";"); //清除连续分号 6 s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白 7 return (s == null) ? "" : s[1]; 8 }
27、原生JavaScript获取当前路径
28、原生JavaScriptIP转成整型
29、原生JavaScript整型解析为IP地址
30、原生JavaScript实现checkbox全选与全不选
1 function checkAll() { 2 var selectall = document.getElementById("selectall"); 3 var allbox = document.getElementsByName("allbox"); 4 if (selectall.checked) { 5 for (var i = 0; i < allbox.length; i++) { 6 allbox[i].checked = true; 7 } 8 } else { 9 for (var i = 0; i < allbox.length; i++) { 10 allbox[i].checked = false; 11 } 12 } 13 }
100个直接可以拿来用的JavaScript实用功能代码片段(二)
已有 0 人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐