欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript常用工具函数大全

程序员文章站 2022-06-07 23:14:23
本文实例总结了javascript常用工具函数。分享给大家供大家参考,具体如下:为元素添加on方法element.prototype.on = element.prototype.addeventli...

本文实例总结了javascript常用工具函数。分享给大家供大家参考,具体如下:

为元素添加on方法

element.prototype.on = element.prototype.addeventlistener;

nodelist.prototype.on = function (event, fn) {、
 []['foreach'].call(this, function (el) {
  el.on(event, fn);
 });
 return this;
};

为元素添加trigger方法

element.prototype.trigger = function(type, data) {
 var event = document.createevent("htmlevents");
 event.initevent(type, true, true);
 event.data = data || {};
 event.eventname = type;
 event.target = this;
 this.dispatchevent(event);
 return this;
};

nodelist.prototype.trigger = function(event) {
 []["foreach"].call(this, function(el) {
 el["trigger"](event);
 });
 return this;
};

转义html标签

function htmlencode(text) {
 return text
 .replace(/&/g, "&")
 .replace(/\"/g, '"')
 .replace(/</g, "<")
 .replace(/>/g, ">");
}

html标签转义

// html 标签转义
// @param {array.<domstring>} templatedata 字符串类型的tokens
// @param {...} ..vals 表达式占位符的运算结果tokens
//
function saferhtml(templatedata) {
 var s = templatedata[0];
 for (var i = 1; i < arguments.length; i++) {
 var arg = string(arguments[i]);
 // escape special characters in the substitution.
 s += arg
  .replace(/&/g, "&amp;")
  .replace(/</g, "&lt;")
  .replace(/>/g, "&gt;");
 // don't escape special characters in the template.
 s += templatedata[i];
 }
 return s;
}
// 调用
var html = saferhtml`<p>这是关于字符串模板的介绍</p>`;

跨浏览器绑定事件

function addeventsamp(obj, evt, fn) {
 if (!otarget) {
 return;
 }
 if (obj.addeventlistener) {
 obj.addeventlistener(evt, fn, false);
 } else if (obj.attachevent) {
 obj.attachevent("on" + evt, fn);
 } else {
 otarget["on" + sevttype] = fn;
 }
}

加入收藏夹

function addfavorite(surl, stitle) {
 try {
 window.external.addfavorite(surl, stitle);
 } catch (e) {
 try {
  window.sidebar.addpanel(stitle, surl, "");
 } catch (e) {
  alert("加入收藏失败,请使用ctrl+d进行添加");
 }
 }
}

提取页面代码中所有网址

var aa = document.documentelement.outerhtml
 .match(
 /(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\] ]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\] ]+)/gi
 )
 .join("\r\n")
 .replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\) ]*$/gim, "");
alert(aa);

动态加载脚本文件

function appendscript(src, text, reload, charset) {
 var id = hash(src + text);
 if (!reload && in_array(id, evalscripts)) return;
 if (reload && $(id)) {
 $(id).parentnode.removechild($(id));
 }

 evalscripts.push(id);
 var scriptnode = document.createelement("script");
 scriptnode.type = "text/javascript";
 scriptnode.id = id;
 scriptnode.charset = charset
 ? charset
 : browser.firefox
 ? document.characterset
 : document.charset;
 try {
 if (src) {
  scriptnode.src = src;
  scriptnode.onloaddone = false;
  scriptnode.onload = function() {
  scriptnode.onloaddone = true;
  jsloaded[src] = 1;
  };
  scriptnode.onreadystatechange = function() {
  if (
   (scriptnode.readystate == "loaded" ||
   scriptnode.readystate == "complete") &&
   !scriptnode.onloaddone
  ) {
   scriptnode.onloaddone = true;
   jsloaded[src] = 1;
  }
  };
 } else if (text) {
  scriptnode.text = text;
 }
 document.getelementsbytagname("head")[0].appendchild(scriptnode);
 } catch (e) {}
}

返回顶部的通用方法

function backtop(btnid) {
 var btn = document.getelementbyid(btnid);
 var d = document.documentelement;
 var b = document.body;
 window.onscroll = set;
 btn.style.display = "none";
 btn.onclick = function() {
 btn.style.display = "none";
 window.onscroll = null;
 this.timer = setinterval(function() {
  d.scrolltop -= math.ceil((d.scrolltop + b.scrolltop) * 0.1);
  b.scrolltop -= math.ceil((d.scrolltop + b.scrolltop) * 0.1);
  if (d.scrolltop + b.scrolltop == 0)
  clearinterval(btn.timer, (window.onscroll = set));
 }, 10);
 };
 function set() {
 btn.style.display = d.scrolltop + b.scrolltop > 100 ? "block" : "none";
 }
}
backtop("gotop");

实现base64解码

function base64_decode(data) {
 var b64 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/=";
 var o1,
 o2,
 o3,
 h1,
 h2,
 h3,
 h4,
 bits,
 i = 0,
 ac = 0,
 dec = "",
 tmp_arr = [];
 if (!data) {
 return data;
 }
 data += "";
 do {
 h1 = b64.indexof(data.charat(i++));
 h2 = b64.indexof(data.charat(i++));
 h3 = b64.indexof(data.charat(i++));
 h4 = b64.indexof(data.charat(i++));
 bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
 o1 = (bits >> 16) & 0xff;
 o2 = (bits >> 8) & 0xff;
 o3 = bits & 0xff;
 if (h3 == 64) {
  tmp_arr[ac++] = string.fromcharcode(o1);
 } else if (h4 == 64) {
  tmp_arr[ac++] = string.fromcharcode(o1, o2);
 } else {
  tmp_arr[ac++] = string.fromcharcode(o1, o2, o3);
 }
 } while (i < data.length);
 dec = tmp_arr.join("");
 dec = utf8_decode(dec);
 return dec;
}

确认是否是键盘有效输入值

function checkkey(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*/
 return false;
}

全角半角转换

//icase: 0全到半,1半到全,其他不转化
function chgcase(sstr, icase) {
 if (
 typeof sstr != "string" ||
 sstr.length <= 0 ||
 !(icase === 0 || icase == 1)
 ) {
 return sstr;
 }
 var i,
 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));
 }
 }
 return ors.join("");
}

版本对比

function compareversion(v1, v2) {
 v1 = v1.split(".");
 v2 = v2.split(".");

 var len = math.max(v1.length, v2.length);

 while (v1.length < len) {
 v1.push("0");
 }

 while (v2.length < len) {
 v2.push("0");
 }

 for (var i = 0; i < len; i++) {
 var num1 = parseint(v1[i]);
 var num2 = parseint(v2[i]);

 if (num1 > num2) {
  return 1;
 } else if (num1 < num2) {
  return -1;
 }
 }
 return 0;
}

压缩css样式代码

function compresscss(s) {
 //压缩代码
 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释
 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
 s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理
 s = s.replace(/;\s*;/g, ";"); //清除连续分号
 s = s.match(/^\s*(\s+(\s+\s+)*)\s*$/); //去掉首尾空白
 return s == null ? "" : s[1];
}

获取当前路径

var currentpageurl = "";
if (typeof this.href === "undefined") {
 currentpageurl = document.location.tostring().tolowercase();
} else {
 currentpageurl = this.href.tostring().tolowercase();
}

字符串长度截取

function cutstr(str, len) {
 var temp,
  icount = 0,
  patrn = /[^\x00-\xff]/,
  strre = "";
 for (var i = 0; i < str.length; i++) {
  if (icount < len - 1) {
   temp = str.substr(i, 1);
    if (patrn.exec(temp) == null) {
     icount = icount + 1
   } else {
    icount = icount + 2
   }
   strre += temp
   } else {
   break;
  }
 }
 return strre + "..."
}

时间日期格式转换

date.prototype.format = function(formatstr) {
 var str = formatstr;
 var week = ["日", "一", "二", "三", "四", "五", "六"];
 str = str.replace(/yyyy|yyyy/, this.getfullyear());
 str = str.replace(
 /yy|yy/,
 this.getyear() % 100 > 9
  ? (this.getyear() % 100).tostring()
  : "0" + (this.getyear() % 100)
 );
 str = str.replace(
 /mm/,
 this.getmonth() + 1 > 9
  ? (this.getmonth() + 1).tostring()
  : "0" + (this.getmonth() + 1)
 );
 str = str.replace(/m/g, this.getmonth() + 1);
 str = str.replace(/w|w/g, week[this.getday()]);
 str = str.replace(
 /dd|dd/,
 this.getdate() > 9 ? this.getdate().tostring() : "0" + this.getdate()
 );
 str = str.replace(/d|d/g, this.getdate());
 str = str.replace(
 /hh|hh/,
 this.gethours() > 9 ? this.gethours().tostring() : "0" + this.gethours()
 );
 str = str.replace(/h|h/g, this.gethours());
 str = str.replace(
 /mm/,
 this.getminutes() > 9
  ? this.getminutes().tostring()
  : "0" + this.getminutes()
 );
 str = str.replace(/m/g, this.getminutes());
 str = str.replace(
 /ss|ss/,
 this.getseconds() > 9
  ? this.getseconds().tostring()
  : "0" + this.getseconds()
 );
 str = str.replace(/s|s/g, this.getseconds());
 return str;
};

// 或
date.prototype.format = function(format) {
 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 k in 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)
  );
 }
 return format;
};
alert(new date().format("yyyy-mm-dd hh:mm:ss"));

跨浏览器删除事件

function delevt(obj, evt, fn) {
 if (!obj) {
 return;
 }
 if (obj.addeventlistener) {
 obj.addeventlistener(evt, fn, false);
 } else if (otarget.attachevent) {
 obj.attachevent("on" + evt, fn);
 } else {
 obj["on" + evt] = fn;
 }
}

判断是否以某个字符串结束

string.prototype.endwith = function(s) {
 var d = this.length - s.length;
 return d >= 0 && this.lastindexof(s) == d;
};

返回脚本内容

function evalscript(s) {
 if (s.indexof("<script") == -1) return s;
 var p = /<script[^\>]*?>([^\x00]*?)<\/script>/gi;
 var arr = [];
 while ((arr = p.exec(s))) {
 var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
 var arr1 = [];
 arr1 = p1.exec(arr[0]);
 if (arr1) {
  appendscript(arr1[1], "", arr1[2], arr1[3]);
 } else {
  p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
  arr1 = p1.exec(arr[0]);
  appendscript("", arr1[2], arr1[1].indexof("reload=") != -1);
 }
 }
 return s;
}

格式化css样式代码

function formatcss(s) {
 //格式化代码
 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
 s = s.replace(/;\s*;/g, ";"); //清除连续分号
 s = s.replace(/\,[\s\.\#\d]*{/g, "{");
 s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2");
 s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2");
 s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2");
 return s;
}

获取cookie值

function getcookie(name) {
 var arr = document.cookie.match(new regexp("(^| )" + name + "=([^;]*)(;|$)"));
 if (arr != null) return unescape(arr[2]);
 return null;
}

获得url中get参数值

// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:get["t1"], get["t2"], get["t3"]
function getget() {
 querystr = window.location.href.split("?");
 if (querystr[1]) {
 gets = querystr[1].split("&");
 get = [];
 for (i = 0; i < gets.length; i++) {
  tmp_arr = gets.split("=");
  key = tmp_arr[0];
  get[key] = tmp_arr[1];
 }
 }
 return querystr[1];
}

获取移动设备初始化大小

function getinitzoom() {
 if (!this._initzoom) {
 var screenwidth = math.min(screen.height, screen.width);
 if (this.isandroidmobiledevice() && !this.isnewchromeonandroid()) {
  screenwidth = screenwidth / window.devicepixelratio;
 }
 this._initzoom = screenwidth / document.body.offsetwidth;
 }
 return this._initzoom;
}

获取页面高度

function getpageheight() {
 var g = document,
 a = g.body,
 f = g.documentelement,
 d = g.compatmode == "backcompat" ? a : g.documentelement;
 return math.max(f.scrollheight, a.scrollheight, d.clientheight);
}

获取页面scrollleft

function getpagescrollleft() {
 var a = document;
 return a.documentelement.scrollleft || a.body.scrollleft;
}

获取页面scrolltop

function getpagescrolltop() {
 var a = document;
 return a.documentelement.scrolltop || a.body.scrolltop;
}

获取页面可视高度

function getpageviewheight() {
 var d = document,
 a = d.compatmode == "backcompat" ? d.body : d.documentelement;
 return a.clientheight;
}

获取页面可视宽度

function getpageviewwidth() {
 var d = document,
 a = d.compatmode == "backcompat" ? d.body : d.documentelement;
 return a.clientwidth;
}

获取页面宽度

function getpagewidth() {
 var g = document,
 a = g.body,
 f = g.documentelement,
 d = g.compatmode == "backcompat" ? a : g.documentelement;
 return math.max(f.scrollwidth, a.scrollwidth, d.clientwidth);
}

获取移动设备屏幕宽度

function getscreenwidth() {
 var smallerside = math.min(screen.width, screen.height);
 var fixviewportsexperiment =
 renderermodel.runningexperiments.fixviewport ||
 renderermodel.runningexperiments.fixviewport;
 var fixviewportsexperimentrunning =
 fixviewportsexperiment && fixviewportsexperiment.tolowercase() === "new";
 if (fixviewportsexperiment) {
 if (this.isandroidmobiledevice() && !this.isnewchromeonandroid()) {
  smallerside = smallerside / window.devicepixelratio;
 }
 }
 return smallerside;
}

获取网页被卷去的位置

function getscrollxy() {
 return document.body.scrolltop
 ? {
  x: document.body.scrollleft,
  y: document.body.scrolltop
  }
 : {
  x: document.documentelement.scrollleft,
  y: document.documentelement.scrolltop
  };
}

获取url上的参数

// 获取url中的某参数值,不区分大小写
// 获取url中的某参数值,不区分大小写,
// 默认是取'hash'里的参数,
// 如果传其他参数支持取‘search'中的参数
// @param {string} name 参数名称
export function geturlparam(name, type = "hash") {
 let newname = name,
 reg = new regexp("(^|&)" + newname + "=([^&]*)(&|$)", "i"),
 paramhash = window.location.hash.split("?")[1] || "",
 paramsearch = window.location.search.split("?")[1] || "",
 param;

 type === "hash" ? (param = paramhash) : (param = paramsearch);

 let result = param.match(reg);

 if (result != null) {
 return result[2].split("/")[0];
 }
 return null;
}

检验url链接是否有效

function geturlstate(url) {
 var xmlhttp = new activexobject("microsoft.xmlhttp");
 xmlhttp.open("get", url, false);
 try {
 xmlhttp.send();
 } catch (e) {
 } finally {
 var result = xmlhttp.responsetext;
 if (result) {
  if (xmlhttp.status == 200) {
  return true;
  } else {
  return false;
  }
 } else {
  return false;
 }
 }
}

获取窗体可见范围的宽与高

function getviewsize() {
 var de = document.documentelement;
 var db = document.body;
 var vieww = de.clientwidth == 0 ? db.clientwidth : de.clientwidth;
 var viewh = de.clientheight == 0 ? db.clientheight : de.clientheight;
 return array(vieww, viewh);
}

获取移动设备最大化大小

function getzoom() {
 var screenwidth =
 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;
 }
 var fixviewportsexperiment =
 renderermodel.runningexperiments.fixviewport ||
 renderermodel.runningexperiments.fixviewport;
 var fixviewportsexperimentrunning =
 fixviewportsexperiment &&
 (fixviewportsexperiment === "new" || fixviewportsexperiment === "new");
 if (fixviewportsexperimentrunning) {
 return screenwidth / window.innerwidth;
 } else {
 return screenwidth / document.body.offsetwidth;
 }
}

判断是否安卓移动设备访问

function isandroidmobiledevice() {
 return /android/i.test(navigator.useragent.tolowercase());
}

判断是否苹果移动设备访问

function isapplemobiledevice() {
 return /iphone|ipod|ipad|macintosh/i.test(navigator.useragent.tolowercase());
}

判断是否为数字类型

function isdigit(value) {
 var patrn = /^[0-9]*$/;
 if (patrn.exec(value) == null || value == "") {
 return false;
 } else {
 return true;
 }
}

是否是某类手机型号

// 用devicepixelratio和分辨率判断
const isiphonex = () => {
 // x xs, xs max, xr
 const xseriesconfig = [
 {
  devicepixelratio: 3,
  width: 375,
  height: 812
 },
 {
  devicepixelratio: 3,
  width: 414,
  height: 896
 },
 {
  devicepixelratio: 2,
  width: 414,
  height: 896
 }
 ];
 // h5
 if (typeof window !== "undefined" && window) {
 const isios = /iphone/gi.test(window.navigator.useragent);
 if (!isios) return false;
 const { devicepixelratio, screen } = window;
 const { width, height } = screen;
 return xseriesconfig.some(
  item =>
  item.devicepixelratio === devicepixelratio &&
  item.width === width &&
  item.height === height
 );
 }
 return false;
};

判断是否移动设备

function ismobile() {
 if (typeof this._ismobile === "boolean") {
 return this._ismobile;
 }
 var screenwidth = this.getscreenwidth();
 var fixviewportsexperiment =
 renderermodel.runningexperiments.fixviewport ||
 renderermodel.runningexperiments.fixviewport;
 var fixviewportsexperimentrunning =
 fixviewportsexperiment && fixviewportsexperiment.tolowercase() === "new";
 if (!fixviewportsexperiment) {
 if (!this.isapplemobiledevice()) {
  screenwidth = screenwidth / window.devicepixelratio;
 }
 }
 var ismobilescreensize = screenwidth < 600;
 var ismobileuseragent = false;
 this._ismobile = ismobilescreensize && this.istouchscreen();
 return this._ismobile;
}

判断吗是否手机号码

function ismobilenumber(e) {
 var i =
  "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178",
 n = "130,131,132,155,156,185,186,145,176",
 a = "133,153,180,181,189,177,173,170",
 o = e || "",
 r = o.substring(0, 3),
 d = o.substring(0, 4),
 s =
  !!/^1\d{10}$/.test(o) &&
  (n.indexof(r) >= 0
  ? "联通"
  : a.indexof(r) >= 0
  ? "电信"
  : "1349" == d
  ? "电信"
  : i.indexof(r) >= 0
  ? "移动"
  : "未知");
 return s;
}

判断是否是移动设备访问

function ismobileuseragent() {
 return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(
 window.navigator.useragent.tolowercase()
 );
}

判断鼠标是否移出事件

function ismouseout(e, handler) {
 if (e.type !== "mouseout") {
 return false;
 }
 var reltg = e.relatedtarget
 ? e.relatedtarget
 : e.type === "mouseout"
 ? e.toelement
 : e.fromelement;
 while (reltg && reltg !== handler) {
 reltg = reltg.parentnode;
 }
 return reltg !== handler;
}

判断是否touch屏幕

function istouchscreen() {
 return (
 "ontouchstart" in window ||
 (window.documenttouch && document instanceof documenttouch)
 );
}

判断是否为网址

function isurl(strurl) {
 var regular = /^\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)) {
 return true;
 } else {
 return false;
 }
}

判断是否打开视窗

function isviewportopen() {
 return !!document.getelementbyid("wixmobileviewport");
}

加载样式文件

function loadstyle(url) {
 try {
 document.createstylesheet(url);
 } catch (e) {
 var csslink = document.createelement("link");
 csslink.rel = "stylesheet";
 csslink.type = "text/css";
 csslink.href = url;
 var head = document.getelementsbytagname("head")[0];
 head.appendchild(csslink);
 }
}

替换地址栏

function locationreplace(url) {
 if (history.replacestate) {
 history.replacestate(null, document.title, url);
 history.go(0);
 } else {
 location.replace(url);
 }
}

解决offsetx兼容性问题

// 针对火狐不支持offsetx/y
function getoffset(e) {
 var target = e.target, // 当前触发的目标对象
 eventcoord,
 pagecoord,
 offsetcoord;

 // 计算当前触发元素到文档的距离
 pagecoord = getpagecoord(target);

 // 计算光标到文档的距离
 eventcoord = {
 x: window.pagexoffset + e.clientx,
 y: window.pageyoffset + e.clienty
 };

 // 相减获取光标到第一个定位的父元素的坐标
 offsetcoord = {
 x: eventcoord.x - pagecoord.x,
 y: eventcoord.y - pagecoord.y
 };
 return offsetcoord;
}

function getpagecoord(element) {
 var coord = { x: 0, y: 0 };
 // 计算从当前触发元素到根节点为止,
 // 各级 offsetparent 元素的 offsetleft 或 offsettop 值之和
 while (element) {
 coord.x += element.offsetleft;
 coord.y += element.offsettop;
 element = element.offsetparent;
 }
 return coord;
}

打开一个窗体通用方法

function openwindow(url, windowname, width, height) {
 var x = parseint(screen.width / 2.0) - width / 2.0;
 var y = parseint(screen.height / 2.0) - height / 2.0;
 var ismsie = navigator.appname == "microsoft internet explorer";
 if (ismsie) {
 var p = "resizable=1,location=no,scrollbars=no,width=";
 p = p + width;
 p = p + ",height=";
 p = p + height;
 p = p + ",left=";
 p = p + x;
 p = p + ",top=";
 p = p + y;
 retval = window.open(url, windowname, p);
 } else {
 var win = window.open(
  url,
  "zyiispopup",
  "top=" +
  y +
  ",left=" +
  x +
  ",scrollbars=" +
  scrollbars +
  ",dialog=yes,modal=yes,width=" +
  width +
  ",height=" +
  height +
  ",resizable=no"
 );
 eval("try { win.resizeto(width, height); } catch(e) { }");
 win.focus();
 }
}

将键值对拼接成url带参数

export default const fnparams2url = obj=> {
  let aurl = []
  let fnadd = function(key, value) {
  return key + '=' + value
  }
  for (var k in obj) {
  aurl.push(fnadd(k, obj[k]))
  }
  return encodeuricomponent(aurl.join('&'))
 }

去掉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;
}

替换全部

string.prototype.replaceall = function(s1, s2) {
 return this.replace(new regexp(s1, "gm"), s2);
};

resize的操作

(function() {
 var fn = function() {
 var w = document.documentelement
  ? document.documentelement.clientwidth
  : document.body.clientwidth,
  r = 1255,
  b = element.extend(document.body),
  classname = b.classname;
 if (w < r) {
  //当窗体的宽度小于1255的时候执行相应的操作
 } else {
  //当窗体的宽度大于1255的时候执行相应的操作
 }
 };
 if (window.addeventlistener) {
 window.addeventlistener("resize", function() {
  fn();
 });
 } else if (window.attachevent) {
 window.attachevent("onresize", function() {
  fn();
 });
 }
 fn();
})();

滚动到顶部

// 使用document.documentelement.scrolltop 或 document.body.scrolltop 获取到顶部的距离,从顶部
// 滚动一小部分距离。使用window.requestanimationframe()来滚动。
// @example
// scrolltotop();
function scrolltotop() {
 var c = document.documentelement.scrolltop || document.body.scrolltop;

 if (c > 0) {
 window.requestanimationframe(scrolltotop);
 window.scrollto(0, c - c / 8);
 }
}

设置cookie值

function setcookie(name, value, hours) {
 var d = new date();
 var offset = 8;
 var utc = d.gettime() + d.gettimezoneoffset() * 60000;
 var nd = utc + 3600000 * offset;
 var exp = new date(nd);
 exp.settime(exp.gettime() + hours * 60 * 60 * 1000);
 document.cookie =
 name +
 "=" +
 escape(value) +
 ";path=/;expires=" +
 exp.togmtstring() +
 ";domain=360doc.com;";
}

设为首页

function sethomepage() {
 if (document.all) {
 document.body.style.behavior = "url(#default#homepage)";
 document.body.sethomepage("http://w3cboy.com");
 } else if (window.sidebar) {
 if (window.netscape) {
  try {
  netscape.security.privilegemanager.enableprivilege(
   "universalxpconnect"
  );
  } catch (e) {
  alert(
   "该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true"
  );
  }
 }
 var prefs = components.classes[
  "@mozilla.org/preferences-service;1"
 ].getservice(components.interfaces.nsiprefbranch);
 prefs.setcharpref("browser.startup.homepage", "http://w3cboy.com");
 }
}

按字母排序,对每行进行数组排序

function setsort() {
 var text = k1.value
 .split(/[\r\n]/)
 .sort()
 .join("\r\n"); //顺序
 var test = k1.value
 .split(/[\r\n]/)
 .sort()
 .reverse()
 .join("\r\n"); //反序
 k1.value = k1.value != text ? text : test;
}

延时执行

// 比如 sleep(1000) 意味着等待1000毫秒,还可从 promise、generator、async/await 等角度实现。
// promise
const sleep = time => {
 return new promise(resolve => settimeout(resolve, time));
};

sleep(1000).then(() => {
 console.log(1);
});


// generator
function* sleepgenerator(time) {
 yield new promise(function(resolve, reject) {
 settimeout(resolve, time);
 });
}

sleepgenerator(1000)
 .next()
 .value.then(() => {
 console.log(1);
 });

//async
function sleep(time) {
 return new promise(resolve => settimeout(resolve, time));
}

async function output() {
 let out = await sleep(1000);
 console.log(1);
 return out;
}

output();

function sleep(callback, time) {
 if (typeof callback === "function") {
 settimeout(callback, time);
 }
}

function output() {
 console.log(1);
}

sleep(output, 1000);

判断是否以某个字符串开头

string.prototype.startwith = function(s) {
 return this.indexof(s) == 0;
};

清除脚本内容

function stripscript(s) {
 return s.replace(/<script.*?>.*?<\/script>/gi, "");
}

时间个性化输出功能

/*
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”
*/
function timeformat(time) {
 var date = new date(time),
 curdate = new date(),
 year = date.getfullyear(),
 month = date.getmonth() + 10,
 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 {
 var pasttime = curdate - date,
  pasth = pasttime / 3600000;

 if (pasth > curhour) {
  timestr = month + "月" + day + "日 " + hour + ":" + minute;
 } else if (pasth >= 1) {
  timestr = "今天 " + hour + ":" + minute + "分";
 } else {
  var pastm = curdate.getminutes() - minute;
  if (pastm > 1) {
  timestr = pastm + "分钟前";
  } else {
  timestr = "刚刚";
  }
 }
 }
 return timestr;
}

全角转换为半角函数

function tocdb(str) {
 var result = "";
 for (var i = 0; i < str.length; i++) {
 code = str.charcodeat(i);
 if (code >= 65281 && code <= 65374) {
  result += string.fromcharcode(str.charcodeat(i) - 65248);
 } else if (code == 12288) {
  result += string.fromcharcode(str.charcodeat(i) - 12288 + 32);
 } else {
  result += str.charat(i);
 }
 }
 return result;
}

半角转换为全角函数

function todbc(str) {
 var result = "";
 for (var i = 0; i < str.length; i++) {
 code = str.charcodeat(i);
 if (code >= 33 && code <= 126) {
  result += string.fromcharcode(str.charcodeat(i) + 65248);
 } else if (code == 32) {
  result += string.fromcharcode(str.charcodeat(i) + 12288 - 32);
 } else {
  result += str.charat(i);
 }
 }
 return result;
}

金额大写转换函数

function transform(tranvalue) {
 try {
 var i = 1;
 var dw2 = new array("", "万", "亿"); //大单位
 var dw1 = new array("拾", "佰", "仟"); //小单位
 var dw = new array(
  "零",
  "壹",
  "贰",
  "叁",
  "肆",
  "伍",
  "陆",
  "柒",
  "捌",
  "玖"
 ); 
 //整数部分用
 //以下是小写转换成大写显示在合计大写的文本框中
 //分离整数与小数
 var source = splits(tranvalue);
 var num = source[0];
 var dig = source[1];
 //转换整数部分
 var k1 = 0; //计小单位
 var k2 = 0; //计大单位
 var sum = 0;
 var str = "";
 var len = source[0].length; //整数的长度
 for (i = 1; i <= len; i++) {
  var n = source[0].charat(len - i); //取得某个位数上的数字
  var bn = 0;
  if (len - i - 1 >= 0) {
  bn = source[0].charat(len - i - 1); //取得某个位数前一位上的数字
  }
  sum = sum + number(n);
  if (sum != 0) {
  str = dw[number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面
  if (n == "0") sum = 0;
  }
  if (len - i - 1 >= 0) {
  //在数字范围内
  if (k1 != 3) {
   //加小单位
   if (bn != 0) {
   str = dw1[k1].concat(str);
   }
   k1++;
  } else {
   //不加小单位,加大单位
   k1 = 0;
   var temp = str.charat(0);
   if (temp == "万" || temp == "亿")
   //若大单位前没有数字则舍去大单位
   str = str.substr(1, str.length - 1);
   str = dw2[k2].concat(str);
   sum = 0;
  }
  }
  if (k1 == 3) {
  //小单位到千则大单位进一
  k2++;
  }
 }
 //转换小数部分
 var strdig = "";
 if (dig != "") {
  var n = dig.charat(0);
  if (n != 0) {
  strdig += dw[number(n)] + "角"; //加数字
  }
  var n = dig.charat(1);
  if (n != 0) {
  strdig += dw[number(n)] + "分"; //加数字
  }
 }
 str += "元" + strdig;
 } catch (e) {
 return "0元";
 }
 return str;
}
//拆分整数与小数
function splits(tranvalue) {
 var value = new array("", "");
 temp = tranvalue.split(".");
 for (var i = 0; i < temp.length; i++) {
 value = temp;
 }
 return value;
}

清除空格

string.prototype.trim = function() {
 var reextraspace = /^\s*(.*?)\s+$/;
 return this.replace(reextraspace, "$1");
};

// 清除左空格
function ltrim(s) {
 return s.replace(/^(\s*| *)/, "");
}

// 清除右空格
function rtrim(s) {
 return s.replace(/(\s*| *)$/, "");
}

随机数时间戳

function uniqueid() {
 var a = math.random,
 b = parseint;
 return (
 number(new date()).tostring() + b(10 * a()) + b(10 * a()) + b(10 * a())
 );
}

实现utf8解码

function utf8_decode(str_data) {
 var tmp_arr = [],
 i = 0,
 ac = 0,
 c1 = 0,
 c2 = 0,
 c3 = 0;
 str_data += "";
 while (i < str_data.length) {
 c1 = str_data.charcodeat(i);
 if (c1 < 128) {
  tmp_arr[ac++] = string.fromcharcode(c1);
  i++;
 } else if (c1 > 191 && c1 < 224) {
  c2 = str_data.charcodeat(i + 1);
  tmp_arr[ac++] = string.fromcharcode(((c1 & 31) << 6) | (c2 & 63));
  i += 2;
 } else {
  c2 = str_data.charcodeat(i + 1);
  c3 = str_data.charcodeat(i + 2);
  tmp_arr[ac++] = string.fromcharcode(
  ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
  );
  i += 3;
 }
 }
 return tmp_arr.join("");
}

以下是puxiao投稿推荐的几个函数,用作常见的输入值校验和替换操作,主要针对*地区的校验规则:

校验是否为一个数字,以及该数字小数点位数是否与参数floats一致

校验规则:

  • 若参数floats有值,则校验该数字小数点后的位数。
  • 若参数floats没有值,则仅仅校验是否为数字。
function isnum(value,floats=null){
 let regexp = new regexp(`^[1-9][0-9]*.[0-9]{${floats}}$|^0.[0-9]{${floats}}$`);
 return typeof value === 'number' && floats?regexp.test(string(value)):true;
}
function anysicintlength(minlength,maxlength){
 let result_str = '';
 if(minlength){
  switch(maxlength){
   case undefined:
    result_str = result_str.concat(`{${minlength-1}}`);
    break;
   case null:
    result_str = result_str.concat(`{${minlength-1},}`);
    break;
   default:
    result_str = result_str.concat(`{${minlength-1},${maxlength-1}}`);
  }
 }else{
  result_str = result_str.concat('*');
 }

 return result_str;
}

校验是否为非零的正整数

function isint(value,minlength=null,maxlength=undefined){
 if(!isnum(value)) return false;

 let regexp = new regexp(`^-?[1-9][0-9]${anysicintlength(minlength,maxlength)}$`);
 return regexp.test(value.tostring());
}

校验是否为非零的正整数

function ispint(value,minlength=null,maxlength=undefined) {
 if(!isnum(value)) return false;

 let regexp = new regexp(`^[1-9][0-9]${anysicintlength(minlength,maxlength)}$`);
 return regexp.test(value.tostring());
}

校验是否为非零的负整数

function isnint(value,minlength=null,maxlength=undefined){
 if(!isnum(value)) return false;
 let regexp = new regexp(`^-[1-9][0-9]${anysicintlength(minlength,maxlength)}$`);
 return regexp.test(value.tostring());
}

校验整数是否在取值范围内

校验规则:

  • minint为在取值范围中最小的整数
  • maxint为在取值范围中最大的整数
function checkintrange(value,minint,maxint=9007199254740991){
 return boolean(isint(value) && (boolean(minint!=undefined && minint!=null)?value>=minint:true) && (value<=maxint));
}

校验是否为*手机号

function istel(value) {
 return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.tostring());
}

校验是否为*传真或固定电话号码

function isfax(str) {
 return /^([0-9]{3,4})?[0-9]{7,8}$|^([0-9]{3,4}-)?[0-9]{7,8}$/.test(str);
}

校验是否为邮箱地址

function isemail(str) {
 return /^[a-za-z0-9_-]+@[a-za-z0-9_-]+(\.[a-za-z0-9_-]+)+$/.test(str);
}

校验是否为qq号码

校验规则:

  • 非0开头的5位-13位整数
function isqq(value) {
 return /^[1-9][0-9]{4,12}$/.test(value.tostring());
}

校验是否为网址

校验规则:

  • https://、http://、ftp://、rtsp://、mms://开头、或者没有这些开头
  • 可以没有www开头(或其他二级域名),仅域名
  • 网页地址中允许出现/%*?@&等其他允许的符号
function isurl(str) {
 return /^(https:\/\/|http:\/\/|ftp:\/\/|rtsp:\/\/|mms:\/\/)?[a-za-z0-9_-]+(\.[a-za-z0-9_-]+)+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(str);
}

校验是否为不含端口号的ip地址

校验规则:

  • ip格式为xxx.xxx.xxx.xxx,每一项数字取值范围为0-255
  • 除0以外其他数字不能以0开头,比如02
function isip(str) {
 return /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/.test(str);
}

校验是否为ipv6地址

校验规则:

  • 支持ipv6正常格式
  • 支持ipv6压缩格式
function isipv6(str){
 return boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str));
}

校验是否为*第二代居民身份证

校验规则:

  • 共18位,最后一位可为x(大小写均可)
  • 不能以0开头
  • 出生年月日会进行校验:年份只能为18/19/2*开头,月份只能为01-12,日只能为01-31
function isidcard(str){
 return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9xx]$/.test(str);
}

校验是否为*邮政编码

参数value为数字或字符串

校验规则:

  • 共6位,且不能以0开头
function ispostcode(value){
 return /^[1-9][0-9]{5}$/.test(value.tostring());
}

校验两个参数是否完全相同,包括类型

校验规则:

  • 值相同,数据类型也相同
function same(firstvalue,secondvalue){
 return firstvalue===secondvalue;
}

校验字符的长度是否在规定的范围内

校验规则:

  • minint为在取值范围中最小的长度
  • maxint为在取值范围中最大的长度
function lengthrange(str,minlength,maxlength=9007199254740991) {
 return boolean(str.length >= minlength && str.length <= maxlength);
}

校验字符是否以字母开头

校验规则:

  • 必须以字母开头
  • 开头的字母不区分大小写
function letterbegin(str){
 return /^[a-z]/.test(str);
}

校验字符是否为纯数字(整数)

校验规则:

  • 字符全部为正整数(包含0)
  • 可以以0开头
function purenum(str) {
 return /^[0-9]*$/.test(str);
}
function anysicpunctuation(str){
 if(!str) return null;
 let arr = str.split('').map(item => {
  return item = '\\' + item;
 });
 return arr.join('|');
}
function getpunctuation(str){
 return anysicpunctuation(str) || '\\~|\\`|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\_|\\+|\\=|\\||\\\|\\[|\\]|\\{|\\}|\\;|\\:|\\"|\\\'|\\,|\\<|\\.|\\>|\\/|\\?';
}
function getexcludepunctuation(str){
 let regexp = new regexp(`[${anysicpunctuation(str)}]`,'g');
 return getpunctuation(' ~`!@#$%^&*()-_+=\[]{};:"\',<.>/?'.replace(regexp,''));
}

返回字符串构成种类(字母,数字,标点符号)的数量

lip缩写的由来:l(letter 字母) + i(uint 数字) + p(punctuation 标点符号)

参数punctuation的说明:

  • punctuation指可接受的标点符号集
  • 若需自定义符号集,例如“仅包含中划线和下划线”,将参数设置为"-_"即可
  • 若不传值或默认为null,则内部默认标点符号集为除空格外的其他英文标点符号:~`!@#$%^&*()-_+=[]{};:"',<.>/?
function getliptypes(str,punctuation=null){
 let p_regexp = new regexp('['+getpunctuation(punctuation)+']');
 return /[a-z]/.test(str) + /[0-9]/.test(str) + p_regexp.test(str);
}

校验字符串构成的种类数量是否大于或等于参数num的值。 通常用来校验用户设置的密码复杂程度。

校验规则:

  • 参数num为需要构成的种类(字母、数字、标点符号),该值只能是1-3。
  • 默认参数num的值为1,即表示:至少包含字母,数字,标点符号中的1种
  • 若参数num的值为2,即表示:至少包含字母,数字,标点符号中的2种
  • 若参数num的值为3,即表示:必须同时包含字母,数字,标点符号
  • 参数punctuation指可接受的标点符号集,具体设定可参考getliptypes()方法中关于标点符号集的解释。
function purelip(str,num=1,punctuation=null){
 let regexp = new regexp(`[^a-z0-9|${getpunctuation(punctuation)}]`);
 return boolean(!regexp.test(str) && getliptypes(str,punctuation)>= num);
}

清除所有空格

function clearspaces(str){
 return str.replace(/[ ]/g,'');
}

清除所有中文字符(包括中文标点符号)

function clearcnchars(str){
 return str.replace(/[\u4e00-\u9fa5]/g,'');
}

清除所有中文字符及空格

function clearcncharsandspaces(str){
 return str.replace(/[\u4e00-\u9fa5 ]/g,'');
}

除保留标点符号集以外,清除其他所有英文的标点符号(含空格)

全部英文标点符号为: ~`!@#$%^&*()-_+=[]{};:"',<.>/?

参数excludepunctuation指需要保留的标点符号集,例如若传递的值为'_',即表示清除_以外的其他所有英文标点符号。

function clearpunctuation(str,excludepunctuation=null){
 let regexp = new regexp(`[${getexcludepunctuation(excludepunctuation)}]`,'g');
 return str.replace(regexp,'');
}

校验是否包含空格

function havespace(str) {
 return /[ ]/.test(str);
}

校验是否包含中文字符(包括中文标点符号)

function havecnchars(str){
 return /[\u4e00-\u9fa5]/.test(str);
}

感兴趣的朋友可以使用在线html/css/javascript代码运行工具http://tools.jb51.net/code/htmljsrun测试上述代码运行效果。