js 功能函数集
canrun
目录列表:
1.RandomNum 随机数
2.in_array判断
3.shuffle 数组乱序
4.is_function 是否函数
5.base64_encode 类php base64_encode函数
6.base64_decode 类php base64_decode函数
7.getImageFilesize 获取图片filesize
8.prDates 打印两日期间日期
9.getBetweenDates 获取两日期间所有日期,组成数组返回
10.getClass 获取HTML中的class
11.getScript 动态加载js文件
12.match_all 扩展js的match函数,得到相当g模式下返回子模式的效果
13.htmlToText 和 textToHtml HTML与Text数据转换
14.str_pad 自动填充函数
15.jQuery幻灯片插件
16.图片淡入淡出效果幻灯片
17.eval解析
18.js数组长度count函数
19.js IP格式判断
20.强制数字类型转换
21.浏览器收藏为书签
22.js对象合并
23.ucFirst 首字符大写
24.下拉框添加删除
25.jQuery字体闪动效果
26.js字体闪动效果(同25)
27.css格式化
1.RandomNum 随机数
function RandomNum(under, over){ switch(arguments.length){ case 1: return parseInt(Math.random()*under+1); case 2: return parseInt(Math.random()*(over-under+1) + under); default: return 0; } }
2.in_array判断
Array.prototype.S=String.fromCharCode(2); Array.prototype.in_array=function(e) { var r=new RegExp(this.S+e+this.S); return (r.test(this.S+this.join(this.S)+this.S)); }
3.shuffle 数组乱序
Array.prototype.shuffle = function(){ for(var j, x, l = i = this.length; i; j = parseInt(Math.random() * l), x = this[--i], this[i] = this[j], this[j] = x); return this; };
4.is_function 是否函数
function is_function(fn) { return !!fn && typeof fn != "string" && !fn.nodeName &&fn.constructor != Array && /^[\s[]?function/.test(fn + ""); }
5.base64_encode 类php base64_encode函数
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //使用函数,这个变量是必须的。
function base64_encode(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while ( i < input . length ); return output; }
普通压缩版base64_encode:
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //使用函数,这个变量是必须的。
function base64_encode(input){var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4);chr1=chr2=chr3="";enc1=enc2=enc3=enc4=""}while(i<input.length);return output}
6.base64_decode 类php base64_decode函数(2020.3.20 自动补位修复末尾等号被移除解析失败情况;PS:之前网上传播的都是坑,移除末尾等号要么无法解析,要么解析异常)
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //使用函数,这个变量是必须的。 function base64_decode(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; var padLen = 4 - (input.length % 4); if (padLen != 4) { while(padLen--) { input += '='; } } var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { return ""; } do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output += String.fromCharCode(chr2); } if (enc4 != 64) { output += String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while ( i < input . length ); return output; }
普通压缩版base64_decode:
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //使用函数,这个变量是必须的。 function base64_decode(input){var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;var padLen=4-(input.length%4);if(padLen!=4){while(padLen--){input+="="}}var base64test=/[^A-Za-z0-9\+\/\=]/g;if(base64test.exec(input)){return""}do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output+=String.fromCharCode(chr2)}if(enc4!=64){output+=String.fromCharCode(chr3)}chr1=chr2=chr3="";enc1=enc2=enc3=enc4=""}while(i<input.length);return output};
7.getImageFilesize 获取图片filesize
function getImageFilesize(o) { x = window.XMLHttpRequest ? new window.XMLHttpRequest: new ActiveXObject("MSxml2.XMLHTTP"); x.open("HEAD", o.src, false); x.send(); alert("大小:" + x.getResponseHeader("Content-Length")); }
8.prDates 打印两日期间日期
/* * 打印两日期间日期 * start YYYY-MM-DD * end YYYY-MM-DD * with_start_end 是否包含起止日期,默认包含 */ function prDates(start,end,with_start_end=true){ var getDate=function(str){ var tempDate=new Date(); var list=str.split("-"); tempDate.setFullYear(list[0]); tempDate.setMonth(list[1]-1); tempDate.setDate(list[2]); return tempDate; } var start=getDate(start); var end=getDate(end); if(start>end){ var tempDate=start; start=end; end=tempDate; } if(with_start_end) document.write("<div>"+start.getFullYear()+"-"+(start.getMonth()+1)+"-"+start.getDate()+"</div>"); //start start.setDate(start.getDate()+1); while(!(start.getFullYear()==end.getFullYear()&&start.getMonth()==end.getMonth()&&start.getDate()==end.getDate())){ document.write("<div>"+start.getFullYear()+"-"+(start.getMonth()+1)+"-"+start.getDate()+"</div>"); start.setDate(start.getDate()+1); } if(with_start_end) document.write("<div>"+start.getFullYear()+"-"+(start.getMonth()+1)+"-"+start.getDate()+"</div>"); //end }
9.getBetweenDates 获取两日期间所有日期,组成数组返回
1 /* 2 * 获取两日期间日期 3 * start YYYY-MM-DD 4 * end YYYY-MM-DD 5 * with_start_end 是否包含起止日期,默认包含,值为S表示仅包含起始日期,值为E表示仅包含结束日期 6 * format_month 是否格式化月份1-9成01-09,默认格式化 7 * format_date 是否格式化日期1-9成01-09,默认格式化 8 * @return array 9 */ 10 var getBetweenDates = function(start,end,with_start_end=true,format_month=true,format_date=true){ 11 var getDate=function(str){ 12 var tempDate=new Date(); 13 var list=str.split("-"); 14 tempDate.setFullYear(list[0]); 15 tempDate.setMonth(list[1]-1); 16 tempDate.setDate(list[2]); 17 return tempDate; 18 }; 19 Date.prototype.getFormatDate = function(flag){ 20 return (flag&&this.getDate()<10)?'0'+this.getDate():this.getDate(); 21 }; 22 Date.prototype.getFormatMonth = function(flag){ 23 return (flag&&this.getMonth()<10)?'0'+this.getMonth():this.getMonth(); 24 }; 25 var dates = new Array(); 26 var start=getDate(start); 27 var end=getDate(end); 28 if(start>end){ 29 var tempDate=start; 30 start=end; 31 end=tempDate; 32 } 33 if(with_start_end && with_start_end != 'E') dates.push(start.getFullYear()+"-"+(start.getFormatMonth()+1)+"-"+start.getFormatDate(format_date)); //start 34 start.setDate(start.getDate()+1); 35 while(!(start.getFullYear()==end.getFullYear()&&start.getMonth()==end.getMonth()&&start.getDate()==end.getDate())){ 36 dates.push(start.getFullYear()+"-"+(start.getFormatMonth()+1)+"-"+start.getFormatDate(format_date)); //between 37 start.setDate(start.getDate()+1); 38 } 39 40 if(with_start_end && with_start_end != 'S') dates.push(start.getFullYear()+"-"+(start.getFormatMonth()+1)+"-"+start.getFormatDate(format_date)); //end 41 return dates; 42 }
10.getClass 获取HTML中的class
1 /** 2 * className 类名 3 * tagname HTML标签名,如div,td,ul等 4 * @return Array 所有class对应标签对象组成的数组 5 * @example 6 <div class="abc">abc</div> 7 var abc = getClass('abc'); 8 for(i=0;i<abc.length;i++){ 9 abc[i].style.backgroundColor='red'; 10 } 11 */ 12 function getClass(className,tagname/*='*'*/) { //IE下不能用默认参数
if(typeof tagname == 'undefined') tagname = '*'; //modified 13 if (typeof(getElementsByClassName) == 'function') { 14 return getElementsByClassName(className); 15 } 16 else { 17 var tagname = document.getElementsByTagName(tagname); 18 var tagnameAll = []; 19 for (var i = 0; i < tagname.length; i++) { 20 //if (tagname[i].className == className) {
if(tagname[i].className.indexOf(className) != -1) { //fixed 21 tagnameAll[tagnameAll.length] = tagname[i]; 22 } 23 } 24 return tagnameAll; 25 } 26 }
11.getScript 动态加载js文件
(function(){ var args = arguments; var i = 1; function getScript(url, fn){ var a=document.createElement("script"); a.async = !!arguments[0]; a.src = args[i]; a.onload = a.onreadystatechange = function(c,b){ if (b || !a.readyState || /loaded|complete/.test(a.readyState)){ a.onload = a.onreadystatechange = null; if (fn instanceof Function){ fn(i); } if (args[++i]){ getScript(args[i], fn); } } }; (document.getElementById("zljsc")||document.body).appendChild(a); } getScript(args[i]); })(true, "https://files.cnblogs.com/Zjmainstay/ZjmainstayRunHTML.js", "https://files.cnblogs.com/Zjmainstay/swfobject.js", "https://files.cnblogs.com/Zjmainstay/Zjmainstay_cnblogs_global.js"); //可以追加多个
12.match_all 扩展js的match函数,得到相当g模式下返回子模式的效果
1 /** 2 * 3 * javascript 匹配所有的匹配值,并返回每个匹配携带其子匹配组成的数组。 4 * 返回数组结构:[["{\"a\":99}", "99"], ["{\"a\":86}", "86"], ["{\"a\":124}", "124"]] 5 * @example 6 var str = '[{"a":99},{"a":86},{"a":124}]'; 7 var pattern = /{"a":(\d+)}/gi; 8 var ma = str.match_all(pattern); 9 alert(ma.toSource()); 10 * 11 */ 12 String.prototype.match_all = function(pattern,replace/*=''*/){
replace = replace || ''; //修正ie下不能使用默认参数问题,习惯了,又摔一跤~~ 13 var matches = [];
//换掉eval写法
//pattern = pattern.toString().replace(/(\/.*\/)([a-z]*)g([a-z]*)/i,'$1$2$3');
//pattern = eval(pattern);
14 var patternParse = pattern.toString().match(/\/(.*)\/([a-z]*)g([a-z]*)/i);
15 pattern = new RegExp(patternParse[1], patternParse[2] + patternParse[3]);
16 var match = this.match(pattern); 17 var string = this; 18 while(!!match){ 19 matches.push(match); 20 string = string.replace(pattern,replace); 21 match = string.match(pattern); 22 } 23 return matches; 24 }
13.htmlToText 和 textToHtml HTML与Text数据转换
1 function htmlToText(html) { 2 return html.replace(/\<br(?: \/)?\>/g, '\n').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); 3 } 4 5 function textToHtml(text) { 6 return text.replace(/&/g, '&').replace(/\</g, '<').replace(/\>/g, '>').replace(/\n/g, '<br>'); 7 }
14.str_pad 自动填充函数
1 /** 2 *@param str 初始字符串 3 *@param length 重复长度 4 *@param pad 填充字符 5 *@param type 填充类型 6 *@return str 7 */ 8 function str_pad(str,length=5,pad=' ',type='left'){ 9 if(isNaN(length)) length = 5; 10 length = Math.max(0,(length - str.length)); 11 if(type == 'left'){ 12 for(i=0;i<length;i++){ 13 str = pad + str; 14 } 15 }else { 16 for(i=0;i<length;i++){ 17 str += pad; 18 } 19 } 20 return str; 21 }
15.jQuery幻灯片插件
1 /** 2 * jQuery Plugin 3 * From http://www.jsfoot.com/jquery/images/cj/2012-07-17/694.html 4 * Modify By Zjmainstay, Blog:http://www.cnblogs.com/Zjmainstay 5 * @example $.mySlideShow('myItemid'); //最简形式,默认开启自动切换,轮换时间为2秒(2000毫秒) 6 * @example $.mySlideShow('myItemid',{autoStart:false}); //关闭自动切换 7 * @example $.mySlideShow('myItemid',{switchingTime:3000}); //设置轮换时间 8 */ 9 (function($){ 10 var mySlideShow = function(id,options){ 11 //显示图片函数,根据接收的index值显示相应的内容 12 var showPics = function(index) { //普通切换 13 var nowLeft = -index*sWidth; //根据index值计算ul元素的left值 14 $("#"+id+" ul").stop(true,false).animate({"left":nowLeft},300); //通过animate()调整ul元素滚动到计算出的position 15 $("#"+id+" .btn span").stop(true,false).animate({"opacity":"0.4"},300).eq(index).stop(true,false).animate({"opacity":"1"},300); //为当前的按钮切换到选中的效果 16 } 17 var sWidth = $("#"+id).width(); //获取焦点图的宽度(显示面积) 18 var len = $("#"+id+" ul li").length; //获取焦点图个数 19 var index = 0; 20 var picTimer; 21 options = options || {} 22 options.autoStart = (options.autoStart==false) ? false : true; //默认自动播放 23 options.switchingTime = !isNaN(options.switchingTime) ? options.switchingTime : 2000; //自动切换时间,默认2000毫秒 24 25 //以下代码添加数字按钮和按钮后的半透明条,还有上一页、下一页两个按钮 26 var btn = "<div class='btnBg'></div><div class='btn'>"; 27 for(var i=0; i < len; i++) { 28 btn += "<span></span>"; 29 } 30 btn += "</div><div class='preNext pre'></div><div class='preNext next'></div>"; 31 $("#"+id).append(btn); 32 $("#"+id+" .btnBg").css("opacity",0.5); 33 34 //为小按钮添加鼠标滑入事件,以显示相应的内容 35 $("#"+id+" .btn span").css("opacity",0.4).mouseover(function() { 36 index = $("#"+id+" .btn span").index(this); 37 showPics(index); 38 }).eq(0).trigger("mouseover"); 39 40 //上一页、下一页按钮透明度处理 41 $("#"+id+" .preNext").css("opacity",0.2).hover(function() { 42 $(this).stop(true,false).animate({"opacity":"0.5"},300); 43 },function() { 44 $(this).stop(true,false).animate({"opacity":"0.2"},300); 45 }); 46 47 //上一页按钮 48 $("#"+id+" .pre").click(function() { 49 index -= 1; 50 if(index == -1) {index = len - 1;} 51 showPics(index); 52 }); 53 54 //下一页按钮 55 $("#"+id+" .next").click(function() { 56 index += 1; 57 if(index == len) {index = 0;} 58 showPics(index); 59 }); 60 61 //本例为左右滚动,即所有li元素都是在同一排向左浮动,所以这里需要计算出外围ul元素的宽度 62 $("#"+id+" ul").css("width",sWidth * (len)); 63 64 //鼠标滑上焦点图时停止自动播放,滑出时开始自动播放 65 //启用自动轮换 66 if(options.autoStart){ 67 $("#"+id).hover(function() { 68 clearInterval(picTimer); 69 },function() { 70 picTimer = setInterval(function() { 71 showPics(index); 72 index++; 73 if(index == len) {index = 0;} 74 },options.switchingTime); 75 }).trigger("mouseleave"); 76 } 77 } 78 //扩展成jQuery插件 79 $.extend({mySlideShow:mySlideShow}); 80 })(jQuery);
jQuery幻灯片插件演示:(运行此段代码(18))
View Code
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>jquery图片滚动仿QQ商城带左右按钮控制焦点图片切换滚动</title> 6 <meta name="description" content="jquery图片特效制作仿腾讯QQ商城首页banner焦点图片轮播切换效果,带索引按钮控制和左右按钮控制图片切换。jquery下载。" /> 7 <style type="text/css"> 8 *{margin:0;padding:0;} 9 body{font-size:12px;color:#222;font-family:Verdana,Arial,Helvetica,sans-serif;background:#f0f0f0;} 10 .clearfix:after{content: ".";display: block;height: 0;clear: both;visibility: hidden;} 11 .clearfix{zoom:1;} 12 ul,li{list-style:none;} 13 img{border:0;} 14 .wrapper{width:800px;margin:0 auto;padding-bottom:50px;} 15 h1{height:50px;line-height:50px;font-size:22px;font-weight:normal;font-family:"Microsoft YaHei",SimHei;margin-bottom:20px;} 16 /* focus */ 17 #focus{width:800px;height:280px;overflow:hidden;position:relative;} 18 #focus ul{height:380px;position:absolute;} 19 #focus ul li{float:left;width:800px;height:280px;overflow:hidden;position:relative;background:#000;} 20 #focus ul li div{position:absolute;overflow:hidden;} 21 #focus .btnBg{position:absolute;width:800px;height:20px;left:0;bottom:0;background:#000;} 22 #focus .btn{position:absolute;width:780px;height:10px;padding:5px 10px;right:0;bottom:0;text-align:right;} 23 #focus .btn span{display:inline-block;_display:inline;_zoom:1;width:25px;height:10px;_font-size:0;margin-left:5px;cursor:pointer;background:#fff;} 24 #focus .btn span.on{background:#fff;} 25 #focus .preNext{width:45px;height:100px;position:absolute;top:90px;background:url(http://www.jsfoot.com/jquery/demo/2012-07-17/img/sprite.png) no-repeat 0 0;cursor:pointer;} 26 #focus .pre{left:0;} 27 #focus .next{right:0;background-position:right top;} 28 </style> 29 30 <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script> 31 <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery.myslideshow.js"></script> 32 <script type="text/javascript"> 33 (function($){ 34 $(document).ready(function(){ 35 $.mySlideShow('focus'); 36 }); 37 })(jQuery); 38 </script> 39 </head> 40 41 <body> 42 43 <div class="wrapper"> 44 <h1>jquery图片滚动仿QQ商城带左右按钮控制焦点图片切换滚动</h1> 45 46 <div id="focus"> 47 <ul> 48 <li><a href="http://www.jsfoot.com/" target="_blank"><img src="http://www.jsfoot.com/jquery/demo/2012-07-17/img/01.jpg" alt="QQ商城焦点图效果下载" /></a></li> 49 <li><a href="http://www.jsfoot.com/" target="_blank"><img src="http://www.jsfoot.com/jquery/demo/2012-07-17/img/02.jpg" alt="QQ商城焦点图效果教程" /></a></li> 50 <li><a href="http://www.jsfoot.com/" target="_blank"><img src="http://www.jsfoot.com/jquery/demo/2012-07-17/img/03.jpg" alt="jquery商城焦点图效果" /></a></li> 51 <li><a href="http://www.jsfoot.com/" target="_blank"><img src="http://www.jsfoot.com/jquery/demo/2012-07-17/img/04.jpg" alt="jquery商城焦点图代码" /></a></li> 52 <li><a href="http://www.jsfoot.com/" target="_blank"><img src="http://www.jsfoot.com/jquery/demo/2012-07-17/img/05.jpg" alt="jquery商城焦点图源码" /></a></li> 53 </ul> 54 </div><!--focus end--> 55 56 </div><!-- wrapper end --> 57 58 </body> 59 <!-- Copyright http://www.jsfoot.com/jquery/images/cj/2012-07-17/694.html --> 60 <!-- Modify by Zjmainstay --> 61 </html>
16、图片淡入淡出效果幻灯片
1 window.onload = function () 2 { 3 var oBox = document.getElementById("box"); 4 var aUl = document.getElementsByTagName("ul"); 5 var aImg = aUl[0].getElementsByTagName("li"); 6 var aNum = aUl[1].getElementsByTagName("li"); 7 var timer = play = null; 8 var i = index = 0; 9 var bOrder = true; 10 //切换按钮 11 for (i = 0; i < aNum.length; i++) 12 { 13 aNum[i].index = i; 14 aNum[i].onclick = function () 15 { 16 show(this.index) 17 } 18 } 19 20 //鼠标划过关闭定时器 21 oBox.onmouseover = function () 22 { 23 clearInterval(play) 24 }; 25 26 //鼠标离开启动自动播放 27 oBox.onmouseout = function () 28 { 29 //autoPlay() 30 }; 31 32 //自动播放函数 33 function autoPlay () 34 { 35 play = setInterval(function () { 36 //判断播放顺序 37 bOrder ? index++ : index--; 38 39 //正序 40 index >= aImg.length && (index = aImg.length - 2, bOrder = false); 41 42 //倒序 43 index <= 0 && (index = 0, bOrder = true); 44 45 //调用函数 46 show(index) 47 },2000); 48 } 49 //autoPlay();//应用 50 51 //图片切换, 淡入淡出效果 52 function show (a) 53 { 54 index = a; 55 var alpha = 0; 56 for (i = 0; i < aNum.length; i++)aNum[i].className = ""; 57 aNum[index].className = "current"; 58 clearInterval(timer); 59 60 for (i = 0; i < aImg.length; i++) 61 { 62 aImg[i].style.opacity = 0; 63 aImg[i].style.filter = "alpha(opacity=0)"; 64 } 65 66 timer = setInterval(function () { 67 alpha += 5; 68 alpha > 100 && (alpha =100); 69 aImg[index].style.opacity = alpha / 100; 70 aImg[index].style.filter = "alpha(opacity = " + alpha + ")"; 71 alpha == 100 && clearInterval(timer) 72 },50); 73 } 74 };
17、eval解析
1 function parseEval(str){ 2 str = str.replace(/^eval/,''); 3 return eval(str); 4 }
18、js数组长度count函数
1 /** 2 * Javascript 数组长度统计 3 * Javascript 关联数组length为0 4 *@example 5 var arr = []; 6 arr["a"] = 1; 7 arr["b"] = [1,2,3]; 8 alert(arr.length+','+arr.count(true)+','+arr.count()); 9 */ 10 Array.prototype.count = function(mode){ 11 //form http://phpjs.org/functions/count/ 12 function count (mixed_var, mode) { 13 // http://kevin.vanzonneveld.net 14 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 15 // + input by: Waldo Malqui Silva 16 // + bugfixed by: Soren Hansen 17 // + input by: merabi 18 // + improved by: Brett Zamir (http://brett-zamir.me) 19 // + bugfixed by: Olivier Louvignes (http://mg-crea.com/) 20 // * example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE'); 21 // * returns 1: 6 22 // * example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); 23 // * returns 2: 6 24 var key, cnt = 0; 25 26 if (mixed_var === null || typeof mixed_var === 'undefined') { 27 return 0; 28 } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object) { 29 return 1; 30 } 31 32 if (mode === 'COUNT_RECURSIVE') { 33 mode = 1; 34 } 35 if (mode != 1) { 36 mode = 0; 37 } 38 39 for (key in mixed_var) { 40 if (mixed_var.hasOwnProperty(key)) { 41 cnt++; 42 if (mode == 1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object)) { 43 cnt += count(mixed_var[key], 1); //这里改this.count为count,否则会导致嵌套数组未定义错误 44 } 45 } 46 } 47 48 return cnt; 49 } 50 return count(this,mode); 51 }
19、js IP格式判断
1 /** 2 * (?!^0(\.0){3}$) //排除0.0.0.0 3 * (?!^255(\.255){3}$) //排除255.255.255.255 4 * ((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{2})|(\d)) //250-255 或 200-249 或 100-199 或 00-99 或 0-9 5 * 排序从左到右,不可逆。 6 */ 7 function validateIP(str){ 8 return !!str.match(/^(?!^0(\.0){3}$)(?!^255(\.255){3}$)((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{2})|(\d))(\.((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{2})|(\d))){3}$/); 9 }
//改进:
首先多谢 @枕头老爸 在闪存里的评论,激发了我简写的冲动,嘻...
function validateIP(str){
return !!str.match(/^(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{2})|(\d))($|(?!\.$)\.)){4}$/);
}
//红色标明部分表示(结束($) 或(|) 不是以点结束((?!\.$))的加上点(\.))
20、强制数字类型转换
1 function getNum(num){ 2 if(typeof(num) == 'undefined' || !num || !num.toString().trim().match(/^\d+(\.\d+)?$/)) return 0; 3 return parseFloat(num); 4 }
21、浏览器收藏为书签
1 function createBookmark(sURL,sTitle) { 2 if (document.all && window.external) { 3 window.external.AddFavorite (sURL,sTitle); 4 } 5 else if (window.sidebar) { 6 window.sidebar.addPanel(sTitle,sURL,''); 7 } 8 else { 9 alert ('' 10 +'抱歉,您的浏览器不能自动加入收藏,' 11 +'请用快捷键 Ctrl+D 加入收藏.' 12 ); 13 } 14 }
22、js对象合并
1 /** 2 * js对象合并方法 3 * @example 4 var obj = {}; 5 obj['a'] = 1; 6 obj['b'] = 1; 7 obj['c'] = 1; 8 var obj2 = {"a":2,"e":1}; 9 var obj3 = {"f":2,"g":1}; 10 var arr = {}; 11 arr = obj.join(obj2).join(obj3); 12 console.log(obj); //这里表明obj没被改动 13 console.log(arr); 14 * 15 */ 16 Object.prototype.join = function(obj,override){ 17 function Temp(){} 18 Temp.prototype = this; 19 var self = new Temp(); //js对象赋值是引用赋值,直接使用var self = this;那么后面的self改动将反馈到原obj 20 if(typeof(obj) == 'object'){ 21 if(typeof(override) == 'undefined') override = true; //默认覆盖 22 for(var o in obj){ 23 if(!override && !!self[o]) continue; 24 self[o] = obj[o]; 25 } 26 } 27 return self; 28 }
23、ucFirst 首字符大写
1 function ucFirst(str){ 2 if(!!str) return str[0].toUpperCase() + str.substr(1); 3 else return str; 4 }
24、下拉框添加删除
1 <html> 2 <head> 3 <title>网页特效|111cn.net/左右选择添加删除内容菜单</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 5 </head> 6 <body> 7 <p>选定一项或多项然后点击添加或移除(按住shift或ctrl可以多选),或在选择项上双击进行添加和移除。</p> 8 <form method="post" name="myform"> 9 <table border="0" width="300"> 10 <tr> 11 <td width="40%"> 12 <select style="width:100%;" multiple name="list1" size="12" ondblclick="moveOption(document.myform.list1, document.myform.list2)"> 13 <option value="北京">北京</option> 14 <option value="上海">上海</option> 15 <option value="山东">山东</option> 16 <option value="安徽">安徽</option> 17 <option value="重庆">重庆</option> 18 <option value="福建">福建</option> 19 <option value="甘肃">甘肃</option> 20 <option value="广东">广东</option> 21 <option value="广西">广西</option> 22 <option value="贵州">贵州</option> 23 <option value="海南">海南</option> 24 <option value="河北">河北</option> 25 <option value="黑龙江">黑龙江</option> 26 <option value="河南">河南</option> 27 <option value="湖北">湖北</option> 28 <option value="湖南">湖南</option> 29 <option value="内蒙古">内蒙古</option> 30 <option value="江苏">江苏</option> 31 <option value="江西">江西</option> 32 <option value="吉林">吉林</option> 33 <option value="辽宁">辽宁</option> 34 <option value="宁夏">宁夏</option> 35 <option value="青海">青海</option> 36 <option value="山西">山西</option> 37 <option value="陕西">陕西</option> 38 <option value="四川">四川</option> 39 <option value="天津">天津</option> 40 <option value="西藏">西藏</option> 41 <option value="新疆">新疆</option> 42 <option value="云南">云南</option> 43 <option value="浙江">浙江</option> 44 <option value="香港">香港</option> 45 <option value="澳门">澳门</option> 46 <option value="台湾">台湾</option> 47 <option value="其他">其他</option> 48 </select> 49 </td> 50 <td width="20%" align="center"> 51 <input type="button" value="添加" onclick="moveOption(document.myform.list1, document.myform.list2)"><br><br> 52 <input type="button" value="删除" onclick="moveOption(document.myform.list2, document.myform.list1)"> 53 </td> 54 <td width="40%"> 55 <select style="width:100%;" multiple name="list2" size="12" ondblclick="moveOption(document.myform.list2, document.myform.list1)"> 56 </select> 57 </td> 58 </tr> 59 </table> 60 值:<input type="text" name="city" size="40" value="" /> 61 </form> 62 <script type="text/javascript"> 63 <!-- 64 function moveOption(e1, e2){ 65 try{ 66 for(var i=0;i<e1.options.length;i++){ 67 if(e1.options[i].selected){ 68 var e = e1.options[i]; 69 e2.options.add(new Option(e.text, e.value)); 70 e1.remove(i); 71 i=i-1 72 } 73 } 74 document.myform.city.value=getvalue(document.myform.list2); 75 } 76 catch(e){} 77 } 78 function getvalue(geto){ 79 var allvalue = ""; 80 for(var i=0;i<geto.options.length;i++){ 81 allvalue +=geto.options[i].value + ","; 82 } 83 return allvalue; 84 } 85 //--> 86 </script> 87 </body> 88 </html>
25、jQuery字体闪动效果
1 <html> 2 <head> 3 <title>字体闪烁</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <meta http-equiv="Content-Language" content="zh-CN" /> 6 <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script> 7 <!--<script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-shake.js"></script>--> 8 </head> 9 <body> 10 <style>.red{border:1px solid #d00; background:#ffe9e8; color:#d00;}</style> 11 <div id="shakeDiv">点击闪烁3下...</div> 12 <script type="text/javascript"> 13 /** 14 * jQuery 插件 15 * HTML标签闪动特效 16 * @params ele jQuery对象 17 * @params cls 变换的class 18 * @params times 闪动次数 19 * @example 20 <style>.red{border:1px solid #d00; background:#ffe9e8; color:#d00;}</style> 21 <div id="shakeDiv">闪烁10下...</div> 22 $.shake($("#shakeDiv"),"red",10); 23 */ 24 $.extend({"shake":function(ele, cls, times) { 25 var i = 0, 26 t = false, 27 o = ele.attr("class") + " ", 28 c = "", 29 times = times || 2; 30 if (t) return; 31 t = setInterval(function() { 32 i++; 33 c = i % 2 ? o + cls: o; 34 ele.attr("class", c); 35 if (i == 2 * times) { 36 clearInterval(t); 37 ele.removeClass(cls); 38 } 39 }, 40 200); 41 }}); 42 $("#shakeDiv").click(function(){ 43 $.shake($(this),'red',3); 44 }); 45 </script> 46 </body> 47 </html>
26、js字体闪动效果
1 <html> 2 <head> 3 <title>js字体闪动效果</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <meta http-equiv="Content-Language" content="zh-CN" /> 6 <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script> 7 </head> 8 <body> 9 <style>.red{border:1px solid #d00; background:#ffe9e8; color:#d00;}</style> 10 <input type="button" value="Shake Me" id="shakeme" onclick="shake(this,'red',3)"/> 11 <script type="text/javascript"> 12 /** 13 * js 字体闪动效果函数 14 * @params id 标签id或dom对象 15 * @params cls 闪动变换的class 16 * @params times 闪动次数 17 * @example 18 //通过id调用方式 19 shake('shakeme','red',3); 20 //通过dom对象调用方式 21 shake(document.getElementById('shakeme'),'red',3); 22 //直接使用this代替 23 <input type="button" value="Shake Me" id="shakeme" onclick="shake(this,'red',3)"/> 24 */ 25 function shake(id,cls,times){ 26 var i = 0, 27 t = false, 28 ele = (typeof id == 'object') ? id : document.getElementById(id), 29 o = ele.className, 30 c = "", 31 times = times || 2; 32 t = setInterval(function() { 33 i++; 34 c = i % 2 ? (o+" "+cls) : o; 35 ele.className = c; 36 if (i == 2 * times) { 37 clearInterval(t); 38 ele.className = o; 39 } 40 }, 41 200); 42 } 43 </script> 44 </body> 45 </html>
27、css格式化
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>CSS格式化</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <meta http-equiv="Content-Language" content="zh-CN" /> 7 </head> 8 <body> 9 <style> 10 .bd_border{width:650px;border: 1px solid #ACCEE0;margin: 0;padding: 3px;text-align: left;} 11 </style> 12 <div class="bd_border"> 13 <table width="100%" border="0" cellspacing="3" cellpadding="0"> 14 <tbody><tr> 15 <td>提供的CSS代码格式化和css在线压缩工具,不需要使用YUI Compressor 或者 CSSTidy等离线工具,直接在线操作。</td> 16 </tr> 17 <tr> 18 <td> 19 /*请将CSS代码复制到下面*/ 20 <a alt="from" href="http://www.jb51.net/tools/cssyasuo.shtml"> 21 <font color="#0000ff">CSS代码格式化</font> 22 </a> 23 </td> 24 </tr> 25 <tr> 26 <td><textarea style="WIDTH: 100%; HEIGHT: 300px" title="www.jb51.net" id="code"></textarea></td> 27 </tr> 28 <tr> 29 <td> 30 <input type="button" value="格式化" onclick="$('code').value = CSSdecode($('code').value);"> | 31 <input type="button" value="压缩化" onclick="$('code').value = CSSencode($('code').value);"> | 32 <input type="button" value="复制" onclick="window.clipboardData.setData('Text',$('code').value);"> | 33 <input type="button" value="粘贴" onclick="$('code').value = window.clipboardData.getData('Text');"> | 34 <input type="button" value="清空" onclick="$('code').value = ''"> 35 </td> 36 </tr> 37 </tbody></table> 38 </div> 39 <script type="text/javascript"> 40 <!-- 41 function $() { 42 var elements = new Array(); 43 for (var i = 0; i < arguments.length; i++) { 44 var element = arguments[i]; 45 if (typeof element == 'string') 46 element = document.getElementById(element); 47 if (arguments.length == 1) 48 return element; 49 elements.push(element); 50 } 51 return elements; 52 } 53 function CSSencode(code) 54 { 55 code = code.replace(/\n/ig,''); 56 code = code.replace(/(\s){2,}/ig,'$1'); 57 code = code.replace(/\t/ig,''); 58 code = code.replace(/\n\}/ig,'\}'); 59 code = code.replace(/\n\{\s*/ig,'\{'); 60 code = code.replace(/(\S)\s*\}/ig,'$1\}'); 61 code = code.replace(/(\S)\s*\{/ig,'$1\{'); 62 code = code.replace(/\{\s*(\S)/ig,'\{$1'); 63 return code; 64 } 65 function CSSdecode(code) 66 { 67 code = code.replace(/(\s){2,}/ig,'$1'); 68 code = code.replace(/(\S)\s*\{/ig,'$1 {'); 69 code = code.replace(/\*\/(.[^\}\{]*)}/ig,'\*\/\n$1}'); 70 code = code.replace(/\/\*/ig,'\n\/\*'); 71 code = code.replace(/;\s*(\S)/ig,';\n\t$1'); 72 code = code.replace(/\}\s*(\S)/ig,'\}\n$1'); 73 code = code.replace(/\n\s*\}/ig,'\n\}'); 74 code = code.replace(/\{\s*(\S)/ig,'\{\n\t$1'); 75 code = code.replace(/(\S)\s*\*\//ig,'$1\*\/'); 76 code = code.replace(/\*\/\s*([^\}\{]\S)/ig,'\*\/\n$1'); //modified '\*\/\n\t$1'=>'\*\/\n$1' 77 code = code.replace(/(\S)\}/ig,'$1\n\}'); 78 code = code.replace(/(\n){2,}/ig,'\n'); 79 code = code.replace(/:/ig,': '); 80 code = code.replace(/ /ig,' '); 81 code = code.replace(/^\n*/ig,''); //Add 82 return code; 83 } 84 //--> 85 </script> 86 </body> 87 </html>
代码压缩工具:js代码格式化工具
PS:欢迎评论,我一定会追加您贡献的方法哦。