以前写的几个工具函数。
1.单位转换。如byteTrans(1024) =>1kb; byteTrans(1024,'kb') =>1mb; byteTrans(11111111)=>10.60mb; byteTrans(11111111,"mb")=>10.60tb
function byteTrans (sizeNum,byteStr) { if(sizeNum == null || sizeNum == undefined ||sizeNum == ''){ return '0b'; } sizeNum = parseFloat(sizeNum); var resNum = sizeNum; var byteStrArr = ['b','kb','mb','gb','tb']; var byteIndex; var i; var byteLen = byteStrArr.length; if(byteStr == null){ byteIndex = 0; }else{ byteStr = byteStr.toLowerCase();//转化为小写 for(i = 0;i<byteLen;i++){ if(byteStrArr[i] == byteStr){ byteIndex = i; break; }else{ byteIndex = 0; } } } while(resNum>=1024){ resNum = resNum/1024; byteIndex++; } resNum = resNum.toFixed(2); return resNum + byteStrArr[byteIndex]; }
注。如果是秒级的时间戳。请把ms*1000来使用函数。
var now = new Date().getTime();
var time1 =getDate(now- 60000).time; //"2016-03-09 23:27:25"
var time2 = getDate(now).time;//"2016-03-09 23:28:25"
function getDate(ms){ var res,today,year,month,day,hour,minute,second; if(ms!=undefined){ today = new Date() today.setTime(ms); }else{ today = new Date(); } year = today.getFullYear(); month = today.getMonth() + 1; day = today.getDate(); hour = today.getHours(); minute = today.getMinutes(); second = today.getSeconds(); month = month<10?"0"+month:month; day = day<10?"0"+day:day; hour = hour<10?"0"+hour:hour; minute = minute<10?"0"+minute:minute; second = second<10?"0"+second:second; res={ 'y':year, 'M':month, 'd':day, 'h':hour, "m":minute, "s":second, "time":year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second, "date":year+"-"+month+"-"+day } return res; }
3.设置图片的宽或高的最大值。有时候图片很宽或很长。 我们可以给图片设置一个高和宽的极值,另一边自动适应。
function autoImgSize(img,size){ if(!size){ size=1000;//设置默认最大值为1000 } var imgobj= document.getElementById(img); //获取对象 imgobj.style.width = "auto"; imgobj.style.height = "auto"; //释放图片本来的大小 var imgwidth=imgobj.width; var imgheight=imgobj.height; if(imgwidth>imgheight){ //判断是width和height哪一个大。大的先处理。设置最大值size if(imgwidth>size){ imgobj.style.width = size + "px"; } imgheight=imgobj.height; if(imgheight>size){ imgobj.style.height = size + "px"; } }else{ if(imgheight>size){ imgobj.style.height = size + "px"; } imgwidth=imgobj.width; if(imgwidth>size){ imgobj.style.width = size + "px"; } } }
传入数组,每页的容量,要获取哪一页的数据。 返回上一页、下一页的页码。当前页的数据内容。总页数。
//js分页函数 function jsPage(Arr,pagesize,page){ if(!(Object.prototype.toString.call(Arr) === '[object Array]')){ return } pagesize = parseInt(pagesize); if(isNaN(pagesize)){ pagesize = 10; } if(pagesize <1){ pagesize = 10; } var total = Arr.length; var pagenum = Math.ceil(total/pagesize); var prepage,nextpage,offset,end,pageData,Res; if(pagenum == 0){ pagenum = 1; } prepage = page-1; nextpage = page+1; page = parseInt(page); if(isNaN(page)){ page = 1; } page = page <1?1:page; page = page>pagenum?pagenum:page; offset = (page - 1)*pagesize; end = offset +pagesize; pageData = Arr.slice(offset,end); Res={ pagenum:pagenum, prepage:prepage, nextpage:nextpage, pageData:pageData } return Res; }