JavaScript 常用工具函数

亦凉 2022-10-13 05:08 258阅读 0赞

在这里插入图片描述

目录

    1. 为元素添加 on 方法
    1. 为元素添加trigger方法
    1. 转义 HTML 标签
    1. HTML 标签转义
    1. 跨浏览器绑定事件
    1. 加入收藏夹
    1. 提取页面代码中所有网址
    1. 动态加载脚本文件
    1. 返回顶部的通用方法
    1. 实现base64解码
    1. 确认是否是键盘有效输入值
    1. 全角半角转换
    1. 版本对比
    1. 压缩CSS样式代码
    1. 获取当前路径
    1. 字符串长度截取
    1. 时间日期格式转换
    1. 跨浏览器删除事件
    1. 判断是否以某个字符串结束
    1. 返回脚本内容
    1. 格式化CSS样式代码
    1. 获取Cookie值
    1. 获得URL中GET参数值
    1. 获取移动设备初始化大小
    1. 获取页面高度
    1. 获取页面scrollLeft
    1. 获取页面scrollTop
    1. 获取页面可视高度
    1. 获取页面可视宽度
    1. 获取页面宽度
    1. 获取移动设备屏幕宽度
    1. 获取网页被卷去的位置
    1. 获取URL上的参数
    1. 检验URL链接是否有效
    1. 获取窗体可见范围的宽与高
    1. 获取移动设备最大化大小
    1. 判断是否安卓移动设备访问
    1. 判断是否苹果移动设备访问
    1. 判断是否为数字类型
    1. 是否是某类手机型号
    1. 判断是否移动设备
    1. 判断是否手机号码
    1. 判断是否是移动设备访问
    1. 判断鼠标是否移出事件
    1. 判断是否Touch屏幕
    1. 判断是否为网址
    1. 判断是否打开视窗
    1. 加载样式文件
    1. 替换地址栏
    1. 解决offsetX兼容性问题
    1. 打开一个窗体通用方法
    1. 将键值对拼接成URL带参数
    1. 去掉url前缀
    1. 替换全部
    1. resize的操作
    1. 滚动到顶部
    1. 设置Cookie值
    1. 设为首页
    1. 按字母排序,对每行进行数组排序
    1. 延时执行
    1. 判断是否以某个字符串开头
    1. 清除脚本内容
    1. 时间个性化输出功能
    1. 全角转换为半角函数
    1. 半角转换为全角
    1. 金额大写转换函数
    1. 清除空格
    1. 随机数时间戳
    1. 实现utf8解码

1. 为元素添加 on 方法

  1. Element.prototype.on = Element.prototype.addEventListener;
  2. NodeList.prototype.on = function (event, fn) {
  3. []['forEach'].call(this, function (el) {
  4. el.on(event, fn);
  5. });
  6. return this;
  7. };

2. 为元素添加trigger方法

  1. Element.prototype.trigger = function(type, data) {
  2. var event = document.createEvent("HTMLEvents");
  3. event.initEvent(type, true, true);
  4. event.data = data || { };
  5. event.eventName = type;
  6. event.target = this;
  7. this.dispatchEvent(event);
  8. return this;
  9. };
  10. NodeList.prototype.trigger = function(event) {
  11. []["forEach"].call(this, function(el) {
  12. el["trigger"](event);
  13. });
  14. return this;
  15. };

3. 转义 HTML 标签

  1. function HtmlEncode(text) {
  2. return text
  3. .replace(/&/g, "&")
  4. .replace(/\"/g, '"')
  5. .replace(/</g, "<")
  6. .replace(/>/g, ">");
  7. }

4. HTML 标签转义

  1. // HTML 标签转义
  2. // @param {Array.<DOMString>} templateData 字符串类型的tokens
  3. // @param {...} ..vals 表达式占位符的运算结果tokens
  4. //
  5. function SaferHTML(templateData) {
  6. var s = templateData[0];
  7. for (var i = 1; i < arguments.length; i++) {
  8. var arg = String(arguments[i]);
  9. // Escape special characters in the substitution.
  10. s += arg
  11. .replace(/&/g, "&")
  12. .replace(/</g, "<")
  13. .replace(/>/g, ">");
  14. // Don't escape special characters in the template.
  15. s += templateData[i];
  16. }
  17. return s;
  18. }
  19. // 调用
  20. var html = SaferHTML`<p>这是关于字符串模板的介绍</p>`;

5. 跨浏览器绑定事件

  1. function addEventSamp(obj, evt, fn) {
  2. if (!oTarget) {
  3. return;
  4. }
  5. if (obj.addEventListener) {
  6. obj.addEventListener(evt, fn, false);
  7. } else if (obj.attachEvent) {
  8. obj.attachEvent("on" + evt, fn);
  9. } else {
  10. oTarget["on" + sEvtType] = fn;
  11. }
  12. }

5. 加入收藏夹

  1. function addFavorite(sURL, sTitle) {
  2. try {
  3. window.external.addFavorite(sURL, sTitle);
  4. } catch (e) {
  5. try {
  6. window.sidebar.addPanel(sTitle, sURL, "");
  7. } catch (e) {
  8. alert("加入收藏失败,请使用Ctrl+D进行添加");
  9. }
  10. }
  11. }

7. 提取页面代码中所有网址

  1. var aa = document.documentElement.outerHTML
  2. .match(
  3. /(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\] ]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\] ]+)/gi
  4. )
  5. .join("\r\n")
  6. .replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\) ]*$/gim, "");
  7. alert(aa);

8. 动态加载脚本文件

  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. evalscripts.push(id);
  8. var scriptNode = document.createElement("script");
  9. scriptNode.type = "text/javascript";
  10. scriptNode.id = id;
  11. scriptNode.charset = charset
  12. ? charset
  13. : BROWSER.firefox
  14. ? document.characterSet
  15. : document.charset;
  16. try {
  17. if (src) {
  18. scriptNode.src = src;
  19. scriptNode.onloadDone = false;
  20. scriptNode.onload = function() {
  21. scriptNode.onloadDone = true;
  22. JSLOADED[src] = 1;
  23. };
  24. scriptNode.onreadystatechange = function() {
  25. if (
  26. (scriptNode.readyState == "loaded" ||
  27. scriptNode.readyState == "complete") &&
  28. !scriptNode.onloadDone
  29. ) {
  30. scriptNode.onloadDone = true;
  31. JSLOADED[src] = 1;
  32. }
  33. };
  34. } else if (text) {
  35. scriptNode.text = text;
  36. }
  37. document.getElementsByTagName("head")[0].appendChild(scriptNode);
  38. } catch (e) { }
  39. }

9. 返回顶部的通用方法

  1. function backTop(btnId) {
  2. var btn = document.getElementById(btnId);
  3. var d = document.documentElement;
  4. var b = document.body;
  5. window.onscroll = set;
  6. btn.style.display = "none";
  7. btn.onclick = function() {
  8. btn.style.display = "none";
  9. window.onscroll = null;
  10. this.timer = setInterval(function() {
  11. d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
  12. b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
  13. if (d.scrollTop + b.scrollTop == 0)
  14. clearInterval(btn.timer, (window.onscroll = set));
  15. }, 10);
  16. };
  17. function set() {
  18. btn.style.display = d.scrollTop + b.scrollTop > 100 ? "block" : "none";
  19. }
  20. }
  21. backTop("goTop");

10. 实现base64解码

  1. function base64_decode(data) {
  2. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3. var o1,
  4. o2,
  5. o3,
  6. h1,
  7. h2,
  8. h3,
  9. h4,
  10. bits,
  11. i = 0,
  12. ac = 0,
  13. dec = "",
  14. tmp_arr = [];
  15. if (!data) {
  16. return data;
  17. }
  18. data += "";
  19. do {
  20. h1 = b64.indexOf(data.charAt(i++));
  21. h2 = b64.indexOf(data.charAt(i++));
  22. h3 = b64.indexOf(data.charAt(i++));
  23. h4 = b64.indexOf(data.charAt(i++));
  24. bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
  25. o1 = (bits >> 16) & 0xff;
  26. o2 = (bits >> 8) & 0xff;
  27. o3 = bits & 0xff;
  28. if (h3 == 64) {
  29. tmp_arr[ac++] = String.fromCharCode(o1);
  30. } else if (h4 == 64) {
  31. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  32. } else {
  33. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  34. }
  35. } while (i < data.length);
  36. dec = tmp_arr.join("");
  37. dec = utf8_decode(dec);
  38. return dec;
  39. }

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

  1. function checkKey(iKey) {
  2. if (iKey == 32 || iKey == 229) {
  3. return true;
  4. } /*空格和异常*/
  5. if (iKey > 47 && iKey < 58) {
  6. return true;
  7. } /*数字*/
  8. if (iKey > 64 && iKey < 91) {
  9. return true;
  10. } /*字母*/
  11. if (iKey > 95 && iKey < 108) {
  12. return true;
  13. } /*数字键盘1*/
  14. if (iKey > 108 && iKey < 112) {
  15. return true;
  16. } /*数字键盘2*/
  17. if (iKey > 185 && iKey < 193) {
  18. return true;
  19. } /*符号1*/
  20. if (iKey > 218 && iKey < 223) {
  21. return true;
  22. } /*符号2*/
  23. return false;
  24. }

12. 全角半角转换

  1. //iCase: 0全到半,1半到全,其他不转化
  2. function chgCase(sStr, iCase) {
  3. if (
  4. typeof sStr != "string" ||
  5. sStr.length <= 0 ||
  6. !(iCase === 0 || iCase == 1)
  7. ) {
  8. return sStr;
  9. }
  10. var i,
  11. oRs = [],
  12. iCode;
  13. if (iCase) {
  14. /*半->全*/
  15. for (i = 0; i < sStr.length; i += 1) {
  16. iCode = sStr.charCodeAt(i);
  17. if (iCode == 32) {
  18. iCode = 12288;
  19. } else if (iCode < 127) {
  20. iCode += 65248;
  21. }
  22. oRs.push(String.fromCharCode(iCode));
  23. }
  24. } else {
  25. /*全->半*/
  26. for (i = 0; i < sStr.length; i += 1) {
  27. iCode = sStr.charCodeAt(i);
  28. if (iCode == 12288) {
  29. iCode = 32;
  30. } else if (iCode > 65280 && iCode < 65375) {
  31. iCode -= 65248;
  32. }
  33. oRs.push(String.fromCharCode(iCode));
  34. }
  35. }
  36. return oRs.join("");
  37. }

13. 版本对比

  1. function compareVersion(v1, v2) {
  2. v1 = v1.split(".");
  3. v2 = v2.split(".");
  4. var len = Math.max(v1.length, v2.length);
  5. while (v1.length < len) {
  6. v1.push("0");
  7. }
  8. while (v2.length < len) {
  9. v2.push("0");
  10. }
  11. for (var i = 0; i < len; i++) {
  12. var num1 = parseInt(v1[i]);
  13. var num2 = parseInt(v2[i]);
  14. if (num1 > num2) {
  15. return 1;
  16. } else if (num1 < num2) {
  17. return -1;
  18. }
  19. }
  20. return 0;
  21. }

14. 压缩CSS样式代码

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

15. 获取当前路径

  1. var currentPageUrl = "";
  2. if (typeof this.href === "undefined") {
  3. currentPageUrl = document.location.toString().toLowerCase();
  4. } else {
  5. currentPageUrl = this.href.toString().toLowerCase();
  6. }

16. 字符串长度截取

  1. function cutstr(str, len) {
  2. var temp,
  3. icount = 0,
  4. patrn = /[^\x00-\xff]/
  5. 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. }

17. 时间日期格式转换

  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(
  6. /yy|YY/,
  7. this.getYear() % 100 > 9
  8. ? (this.getYear() % 100).toString()
  9. : "0" + (this.getYear() % 100)
  10. );
  11. str = str.replace(
  12. /MM/,
  13. this.getMonth() + 1 > 9
  14. ? (this.getMonth() + 1).toString()
  15. : "0" + (this.getMonth() + 1)
  16. );
  17. str = str.replace(/M/g, this.getMonth() + 1);
  18. str = str.replace(/w|W/g, Week[this.getDay()]);
  19. str = str.replace(
  20. /dd|DD/,
  21. this.getDate() > 9 ? this.getDate().toString() : "0" + this.getDate()
  22. );
  23. str = str.replace(/d|D/g, this.getDate());
  24. str = str.replace(
  25. /hh|HH/,
  26. this.getHours() > 9 ? this.getHours().toString() : "0" + this.getHours()
  27. );
  28. str = str.replace(/h|H/g, this.getHours());
  29. str = str.replace(
  30. /mm/,
  31. this.getMinutes() > 9
  32. ? this.getMinutes().toString()
  33. : "0" + this.getMinutes()
  34. );
  35. str = str.replace(/m/g, this.getMinutes());
  36. str = str.replace(
  37. /ss|SS/,
  38. this.getSeconds() > 9
  39. ? this.getSeconds().toString()
  40. : "0" + this.getSeconds()
  41. );
  42. str = str.replace(/s|S/g, this.getSeconds());
  43. return str;
  44. };
  45. // 或
  46. Date.prototype.format = function(format) {
  47. var o = {
  48. "M+": this.getMonth() + 1, //month
  49. "d+": this.getDate(), //day
  50. "h+": this.getHours(), //hour
  51. "m+": this.getMinutes(), //minute
  52. "s+": this.getSeconds(), //second
  53. "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
  54. S: this.getMilliseconds() //millisecond
  55. };
  56. if (/(y+)/.test(format))
  57. format = format.replace(
  58. RegExp.$1,
  59. (this.getFullYear() + "").substr(4 - RegExp.$1.length)
  60. );
  61. for (var k in o) {
  62. if (new RegExp("(" + k + ")").test(format))
  63. format = format.replace(
  64. RegExp.$1,
  65. RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  66. );
  67. }
  68. return format;
  69. };
  70. alert(new Date().format("yyyy-MM-dd hh:mm:ss"));

18. 跨浏览器删除事件

  1. function delEvt(obj, evt, fn) {
  2. if (!obj) {
  3. return;
  4. }
  5. if (obj.addEventListener) {
  6. obj.addEventListener(evt, fn, false);
  7. } else if (oTarget.attachEvent) {
  8. obj.attachEvent("on" + evt, fn);
  9. } else {
  10. obj["on" + evt] = fn;
  11. }
  12. }

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

  1. String.prototype.endWith = function(s) {
  2. var d = this.length - s.length;
  3. return d >= 0 && this.lastIndexOf(s) == d;
  4. };

20. 返回脚本内容

  1. function evalscript(s) {
  2. if (s.indexOf("<script") == -1) return s;
  3. var p = /<script[^\>]*?>([^\x00]*?)<\/script>/gi;
  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. }

21. 格式化CSS样式代码

  1. function formatCss(s) {
  2. //格式化代码
  3. s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
  4. s = s.replace(/;\s*;/g, ";"); //清除连续分号
  5. s = s.replace(/\,[\s\.\#\d]*{/g, "{");
  6. s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2");
  7. s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2");
  8. s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2");
  9. return s;
  10. }

22. 获取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. }

23. 获得URL中GET参数值

  1. // 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]
  2. function getGet() {
  3. querystr = window.location.href.split("?");
  4. if (querystr[1]) {
  5. GETs = querystr[1].split("&");
  6. GET = [];
  7. for (i = 0; i < GETs.length; i++) {
  8. tmp_arr = GETs.split("=");
  9. key = tmp_arr[0];
  10. GET[key] = tmp_arr[1];
  11. }
  12. }
  13. return querystr[1];
  14. }

24. 获取移动设备初始化大小

  1. function getInitZoom() {
  2. if (!this._initZoom) {
  3. var screenWidth = Math.min(screen.height, screen.width);
  4. if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {
  5. screenWidth = screenWidth / window.devicePixelRatio;
  6. }
  7. this._initZoom = screenWidth / document.body.offsetWidth;
  8. }
  9. return this._initZoom;
  10. }

25. 获取页面高度

  1. function getPageHeight() {
  2. var g = document,
  3. a = g.body,
  4. f = g.documentElement,
  5. d = g.compatMode == "BackCompat" ? a : g.documentElement;
  6. return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
  7. }

26. 获取页面scrollLeft

  1. function getPageScrollLeft() {
  2. var a = document;
  3. return a.documentElement.scrollLeft || a.body.scrollLeft;
  4. }

27. 获取页面scrollTop

  1. function getPageScrollTop() {
  2. var a = document;
  3. return a.documentElement.scrollTop || a.body.scrollTop;
  4. }

28. 获取页面可视高度

  1. function getPageViewHeight() {
  2. var d = document,
  3. a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  4. return a.clientHeight;
  5. }

29. 获取页面可视宽度

  1. function getPageViewWidth() {
  2. var d = document,
  3. a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  4. return a.clientWidth;
  5. }

30. 获取页面宽度

  1. function getPageWidth() {
  2. var g = document,
  3. a = g.body,
  4. f = g.documentElement,
  5. d = g.compatMode == "BackCompat" ? a : g.documentElement;
  6. return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
  7. }

31. 获取移动设备屏幕宽度

  1. function getScreenWidth() {
  2. var smallerSide = Math.min(screen.width, screen.height);
  3. var fixViewPortsExperiment =
  4. rendererModel.runningExperiments.FixViewport ||
  5. rendererModel.runningExperiments.fixviewport;
  6. var fixViewPortsExperimentRunning =
  7. fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new";
  8. if (fixViewPortsExperiment) {
  9. if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {
  10. smallerSide = smallerSide / window.devicePixelRatio;
  11. }
  12. }
  13. return smallerSide;
  14. }

32. 获取网页被卷去的位置

  1. function getScrollXY() {
  2. return document.body.scrollTop
  3. ? {
  4. x: document.body.scrollLeft,
  5. y: document.body.scrollTop
  6. }
  7. : {
  8. x: document.documentElement.scrollLeft,
  9. y: document.documentElement.scrollTop
  10. };
  11. }

33. 获取URL上的参数

  1. // 获取URL中的某参数值,不区分大小写
  2. // 获取URL中的某参数值,不区分大小写,
  3. // 默认是取'hash'里的参数,
  4. // 如果传其他参数支持取‘search’中的参数
  5. // @param {String} name 参数名称
  6. export function getUrlParam(name, type = "hash") {
  7. let newName = name,
  8. reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"),
  9. paramHash = window.location.hash.split("?")[1] || "",
  10. paramSearch = window.location.search.split("?")[1] || "",
  11. param;
  12. type === "hash" ? (param = paramHash) : (param = paramSearch);
  13. let result = param.match(reg);
  14. if (result != null) {
  15. return result[2].split("/")[0];
  16. }
  17. return null;
  18. }

34. 检验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. }

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

  1. function getViewSize() {
  2. var de = document.documentElement;
  3. var db = document.body;
  4. var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth;
  5. var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight;
  6. return Array(viewW, viewH);
  7. }

36. 获取移动设备最大化大小

  1. function getZoom() {
  2. var screenWidth =
  3. Math.abs(window.orientation) === 90
  4. ? Math.max(screen.height, screen.width)
  5. : Math.min(screen.height, screen.width);
  6. if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {
  7. screenWidth = screenWidth / window.devicePixelRatio;
  8. }
  9. var FixViewPortsExperiment =
  10. rendererModel.runningExperiments.FixViewport ||
  11. rendererModel.runningExperiments.fixviewport;
  12. var FixViewPortsExperimentRunning =
  13. FixViewPortsExperiment &&
  14. (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new");
  15. if (FixViewPortsExperimentRunning) {
  16. return screenWidth / window.innerWidth;
  17. } else {
  18. return screenWidth / document.body.offsetWidth;
  19. }
  20. }

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

  1. function isAndroidMobileDevice() {
  2. return /android/i.test(navigator.userAgent.toLowerCase());
  3. }

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

  1. function isAppleMobileDevice() {
  2. return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());
  3. }

39. 判断是否为数字类型

  1. function isDigit(value) {
  2. var patrn = /^[0-9]*$/;
  3. if (patrn.exec(value) == null || value == "") {
  4. return false;
  5. } else {
  6. return true;
  7. }
  8. }

40. 是否是某类手机型号

  1. // 用devicePixelRatio和分辨率判断
  2. const isIphonex = () => {
  3. // X XS, XS Max, XR
  4. const xSeriesConfig = [
  5. {
  6. devicePixelRatio: 3,
  7. width: 375,
  8. height: 812
  9. },
  10. {
  11. devicePixelRatio: 3,
  12. width: 414,
  13. height: 896
  14. },
  15. {
  16. devicePixelRatio: 2,
  17. width: 414,
  18. height: 896
  19. }
  20. ];
  21. // h5
  22. if (typeof window !== "undefined" && window) {
  23. const isIOS = /iphone/gi.test(window.navigator.userAgent);
  24. if (!isIOS) return false;
  25. const { devicePixelRatio, screen } = window;
  26. const { width, height } = screen;
  27. return xSeriesConfig.some(
  28. item =>
  29. item.devicePixelRatio === devicePixelRatio &&
  30. item.width === width &&
  31. item.height === height
  32. );
  33. }
  34. return false;
  35. };

41. 判断是否移动设备

  1. function isMobile() {
  2. if (typeof this._isMobile === "boolean") {
  3. return this._isMobile;
  4. }
  5. var screenWidth = this.getScreenWidth();
  6. var fixViewPortsExperiment =
  7. rendererModel.runningExperiments.FixViewport ||
  8. rendererModel.runningExperiments.fixviewport;
  9. var fixViewPortsExperimentRunning =
  10. fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new";
  11. if (!fixViewPortsExperiment) {
  12. if (!this.isAppleMobileDevice()) {
  13. screenWidth = screenWidth / window.devicePixelRatio;
  14. }
  15. }
  16. var isMobileScreenSize = screenWidth < 600;
  17. var isMobileUserAgent = false;
  18. this._isMobile = isMobileScreenSize && this.isTouchScreen();
  19. return this._isMobile;
  20. }

42. 判断是否手机号码

  1. function isMobileNumber(e) {
  2. var i =
  3. "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178",
  4. n = "130,131,132,155,156,185,186,145,176",
  5. a = "133,153,180,181,189,177,173,170",
  6. o = e || "",
  7. r = o.substring(0, 3),
  8. d = o.substring(0, 4),
  9. s =
  10. !!/^1\d{10}$/.test(o) &&
  11. (n.indexOf(r) >= 0
  12. ? "联通"
  13. : a.indexOf(r) >= 0
  14. ? "电信"
  15. : "1349" == d
  16. ? "电信"
  17. : i.indexOf(r) >= 0
  18. ? "移动"
  19. : "未知");
  20. return s;
  21. }

43. 判断是否是移动设备访问

  1. function isMobileUserAgent() {
  2. return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(
  3. window.navigator.userAgent.toLowerCase()
  4. );
  5. }

44. 判断鼠标是否移出事件

  1. function isMouseOut(e, handler) {
  2. if (e.type !== "mouseout") {
  3. return false;
  4. }
  5. var reltg = e.relatedTarget
  6. ? e.relatedTarget
  7. : e.type === "mouseout"
  8. ? e.toElement
  9. : e.fromElement;
  10. while (reltg && reltg !== handler) {
  11. reltg = reltg.parentNode;
  12. }
  13. return reltg !== handler;
  14. }

45. 判断是否Touch屏幕

  1. function isTouchScreen() {
  2. return (
  3. "ontouchstart" in window ||
  4. (window.DocumentTouch && document instanceof DocumentTouch)
  5. );
  6. }

46. 判断是否为网址

  1. function isURL(strUrl) {
  2. 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;
  3. if (regular.test(strUrl)) {
  4. return true;
  5. } else {
  6. return false;
  7. }
  8. }

47. 判断是否打开视窗

  1. function isViewportOpen() {
  2. return !!document.getElementById("wixMobileViewport");
  3. }

48. 加载样式文件

  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. }

49. 替换地址栏

  1. function locationReplace(url) {
  2. if (history.replaceState) {
  3. history.replaceState(null, document.title, url);
  4. history.go(0);
  5. } else {
  6. location.replace(url);
  7. }
  8. }

50. 解决offsetX兼容性问题

  1. // 针对火狐不支持offsetX/Y
  2. function getOffset(e) {
  3. var target = e.target, // 当前触发的目标对象
  4. eventCoord,
  5. pageCoord,
  6. offsetCoord;
  7. // 计算当前触发元素到文档的距离
  8. pageCoord = getPageCoord(target);
  9. // 计算光标到文档的距离
  10. eventCoord = {
  11. X: window.pageXOffset + e.clientX,
  12. Y: window.pageYOffset + e.clientY
  13. };
  14. // 相减获取光标到第一个定位的父元素的坐标
  15. offsetCoord = {
  16. X: eventCoord.X - pageCoord.X,
  17. Y: eventCoord.Y - pageCoord.Y
  18. };
  19. return offsetCoord;
  20. }
  21. function getPageCoord(element) {
  22. var coord = { X: 0, Y: 0 };
  23. // 计算从当前触发元素到根节点为止,
  24. // 各级 offsetParent 元素的 offsetLeft 或 offsetTop 值之和
  25. while (element) {
  26. coord.X += element.offsetLeft;
  27. coord.Y += element.offsetTop;
  28. element = element.offsetParent;
  29. }
  30. return coord;
  31. }

51. 打开一个窗体通用方法

  1. function openWindow(url, windowName, width, height) {
  2. var x = parseInt(screen.width / 2.0) - width / 2.0;
  3. var y = parseInt(screen.height / 2.0) - height / 2.0;
  4. var isMSIE = navigator.appName == "Microsoft Internet Explorer";
  5. if (isMSIE) {
  6. var p = "resizable=1,location=no,scrollbars=no,width=";
  7. p = p + width;
  8. p = p + ",height=";
  9. p = p + height;
  10. p = p + ",left=";
  11. p = p + x;
  12. p = p + ",top=";
  13. p = p + y;
  14. retval = window.open(url, windowName, p);
  15. } else {
  16. var win = window.open(
  17. url,
  18. "ZyiisPopup",
  19. "top=" +
  20. y +
  21. ",left=" +
  22. x +
  23. ",scrollbars=" +
  24. scrollbars +
  25. ",dialog=yes,modal=yes,width=" +
  26. width +
  27. ",height=" +
  28. height +
  29. ",resizable=no"
  30. );
  31. eval("try { win.resizeTo(width, height); } catch(e) { }");
  32. win.focus();
  33. }
  34. }

52. 将键值对拼接成URL带参数

  1. export default const fnParams2Url = obj=> {
  2. let aUrl = []
  3. let fnAdd = function(key, value) {
  4. return key + '=' + value
  5. }
  6. for (var k in obj) {
  7. aUrl.push(fnAdd(k, obj[k]))
  8. }
  9. return encodeURIComponent(aUrl.join('&'))
  10. }

53. 去掉url前缀

  1. function removeUrlPrefix(a) {
  2. a = a
  3. .replace(/:/g, ":")
  4. .replace(/./g, ".")
  5. .replace(///g, "/");
  6. while (
  7. trim(a)
  8. .toLowerCase()
  9. .indexOf("http://") == 0
  10. ) {
  11. a = trim(a.replace(/http:\/\//i, ""));
  12. }
  13. return a;
  14. }

54. 替换全部

  1. String.prototype.replaceAll = function(s1, s2) {
  2. return this.replace(new RegExp(s1, "gm"), s2);
  3. };

55. resize的操作

  1. (function() {
  2. var fn = function() {
  3. var w = document.documentElement
  4. ? document.documentElement.clientWidth
  5. : document.body.clientWidth,
  6. r = 1255,
  7. b = Element.extend(document.body),
  8. classname = b.className;
  9. if (w < r) {
  10. //当窗体的宽度小于1255的时候执行相应的操作
  11. } else {
  12. //当窗体的宽度大于1255的时候执行相应的操作
  13. }
  14. };
  15. if (window.addEventListener) {
  16. window.addEventListener("resize", function() {
  17. fn();
  18. });
  19. } else if (window.attachEvent) {
  20. window.attachEvent("onresize", function() {
  21. fn();
  22. });
  23. }
  24. fn();
  25. })();

56. 滚动到顶部

  1. // 使用document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶部的距离,从顶部
  2. // 滚动一小部分距离。使用window.requestAnimationFrame()来滚动。
  3. // @example
  4. // scrollToTop();
  5. function scrollToTop() {
  6. var c = document.documentElement.scrollTop || document.body.scrollTop;
  7. if (c > 0) {
  8. window.requestAnimationFrame(scrollToTop);
  9. window.scrollTo(0, c - c / 8);
  10. }
  11. }

57. 设置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 =
  9. name +
  10. "=" +
  11. escape(value) +
  12. ";path=/;expires=" +
  13. exp.toGMTString() +
  14. ";domain=360doc.com;";
  15. }

58. 设为首页

  1. function setHomepage() {
  2. if (document.all) {
  3. document.body.style.behavior = "url(#default#homepage)";
  4. document.body.setHomePage("http://w3cboy.com");
  5. } else if (window.sidebar) {
  6. if (window.netscape) {
  7. try {
  8. netscape.security.PrivilegeManager.enablePrivilege(
  9. "UniversalXPConnect"
  10. );
  11. } catch (e) {
  12. alert(
  13. "该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true"
  14. );
  15. }
  16. }
  17. var prefs = Components.classes[
  18. "@mozilla.org/preferences-service;1"
  19. ].getService(Components.interfaces.nsIPrefBranch);
  20. prefs.setCharPref("browser.startup.homepage", "http://w3cboy.com");
  21. }
  22. }

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

  1. function setSort() {
  2. var text = K1.value
  3. .split(/[\r\n]/)
  4. .sort()
  5. .join("\r\n"); //顺序
  6. var test = K1.value
  7. .split(/[\r\n]/)
  8. .sort()
  9. .reverse()
  10. .join("\r\n"); //反序
  11. K1.value = K1.value != text ? text : test;
  12. }

60. 延时执行

  1. // 比如 sleep(1000) 意味着等待1000毫秒,还可从 Promise、Generator、Async/Await 等角度实现。
  2. // Promise
  3. const sleep = time => {
  4. return new Promise(resolve => setTimeout(resolve, time));
  5. };
  6. sleep(1000).then(() => {
  7. console.log(1);
  8. });
  9. // Generator
  10. function* sleepGenerator(time) {
  11. yield new Promise(function(resolve, reject) {
  12. setTimeout(resolve, time);
  13. });
  14. }
  15. sleepGenerator(1000)
  16. .next()
  17. .value.then(() => {
  18. console.log(1);
  19. });
  20. //async
  21. function sleep(time) {
  22. return new Promise(resolve => setTimeout(resolve, time));
  23. }
  24. async function output() {
  25. let out = await sleep(1000);
  26. console.log(1);
  27. return out;
  28. }
  29. output();
  30. function sleep(callback, time) {
  31. if (typeof callback === "function") {
  32. setTimeout(callback, time);
  33. }
  34. }
  35. function output() {
  36. console.log(1);
  37. }
  38. sleep(output, 1000);

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

  1. String.prototype.startWith = function(s) {
  2. return this.indexOf(s) == 0;
  3. };

62. 清除脚本内容

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

63. 时间个性化输出功能

  1. /* 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” */
  2. function timeFormat(time) {
  3. var date = new Date(time),
  4. curDate = new Date(),
  5. year = date.getFullYear(),
  6. month = date.getMonth() + 10,
  7. day = date.getDate(),
  8. hour = date.getHours(),
  9. minute = date.getMinutes(),
  10. curYear = curDate.getFullYear(),
  11. curHour = curDate.getHours(),
  12. timeStr;
  13. if (year < curYear) {
  14. timeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
  15. } else {
  16. var pastTime = curDate - date,
  17. pastH = pastTime / 3600000;
  18. if (pastH > curHour) {
  19. timeStr = month + "月" + day + "日 " + hour + ":" + minute;
  20. } else if (pastH >= 1) {
  21. timeStr = "今天 " + hour + ":" + minute + "分";
  22. } else {
  23. var pastM = curDate.getMinutes() - minute;
  24. if (pastM > 1) {
  25. timeStr = pastM + "分钟前";
  26. } else {
  27. timeStr = "刚刚";
  28. }
  29. }
  30. }
  31. return timeStr;
  32. }

64. 全角转换为半角函数

  1. function toCDB(str) {
  2. var result = "";
  3. for (var i = 0; i < str.length; i++) {
  4. code = str.charCodeAt(i);
  5. if (code >= 65281 && code <= 65374) {
  6. result += String.fromCharCode(str.charCodeAt(i) - 65248);
  7. } else if (code == 12288) {
  8. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  9. } else {
  10. result += str.charAt(i);
  11. }
  12. }
  13. return result;
  14. }

65. 半角转换为全角

  1. function toDBC(str) {
  2. var result = "";
  3. for (var i = 0; i < str.length; i++) {
  4. code = str.charCodeAt(i);
  5. if (code >= 33 && code <= 126) {
  6. result += String.fromCharCode(str.charCodeAt(i) + 65248);
  7. } else if (code == 32) {
  8. result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
  9. } else {
  10. result += str.charAt(i);
  11. }
  12. }
  13. return result;
  14. }

66. 金额大写转换函数

  1. function transform(tranvalue) {
  2. try {
  3. var i = 1;
  4. var dw2 = new Array("", "万", "亿"); //大单位
  5. var dw1 = new Array("拾", "佰", "仟"); //小单位
  6. var dw = new Array(
  7. "零",
  8. "壹",
  9. "贰",
  10. "叁",
  11. "肆",
  12. "伍",
  13. "陆",
  14. "柒",
  15. "捌",
  16. "玖"
  17. );
  18. //整数部分用
  19. //以下是小写转换成大写显示在合计大写的文本框中
  20. //分离整数与小数
  21. var source = splits(tranvalue);
  22. var num = source[0];
  23. var dig = source[1];
  24. //转换整数部分
  25. var k1 = 0; //计小单位
  26. var k2 = 0; //计大单位
  27. var sum = 0;
  28. var str = "";
  29. var len = source[0].length; //整数的长度
  30. for (i = 1; i <= len; i++) {
  31. var n = source[0].charAt(len - i); //取得某个位数上的数字
  32. var bn = 0;
  33. if (len - i - 1 >= 0) {
  34. bn = source[0].charAt(len - i - 1); //取得某个位数前一位上的数字
  35. }
  36. sum = sum + Number(n);
  37. if (sum != 0) {
  38. str = dw[Number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面
  39. if (n == "0") sum = 0;
  40. }
  41. if (len - i - 1 >= 0) {
  42. //在数字范围内
  43. if (k1 != 3) {
  44. //加小单位
  45. if (bn != 0) {
  46. str = dw1[k1].concat(str);
  47. }
  48. k1++;
  49. } else {
  50. //不加小单位,加大单位
  51. k1 = 0;
  52. var temp = str.charAt(0);
  53. if (temp == "万" || temp == "亿")
  54. //若大单位前没有数字则舍去大单位
  55. str = str.substr(1, str.length - 1);
  56. str = dw2[k2].concat(str);
  57. sum = 0;
  58. }
  59. }
  60. if (k1 == 3) {
  61. //小单位到千则大单位进一
  62. k2++;
  63. }
  64. }
  65. //转换小数部分
  66. var strdig = "";
  67. if (dig != "") {
  68. var n = dig.charAt(0);
  69. if (n != 0) {
  70. strdig += dw[Number(n)] + "角"; //加数字
  71. }
  72. var n = dig.charAt(1);
  73. if (n != 0) {
  74. strdig += dw[Number(n)] + "分"; //加数字
  75. }
  76. }
  77. str += "元" + strdig;
  78. } catch (e) {
  79. return "0元";
  80. }
  81. return str;
  82. }
  83. //拆分整数与小数
  84. function splits(tranvalue) {
  85. var value = new Array("", "");
  86. temp = tranvalue.split(".");
  87. for (var i = 0; i < temp.length; i++) {
  88. value = temp;
  89. }
  90. return value;
  91. }

67. 清除空格

  1. String.prototype.trim = function() {
  2. var reExtraSpace = /^\s*(.*?)\s+$/;
  3. return this.replace(reExtraSpace, "$1");
  4. };
  5. // 清除左空格
  6. function ltrim(s) {
  7. return s.replace(/^(\s*| *)/, "");
  8. }
  9. // 清除右空格
  10. function rtrim(s) {
  11. return s.replace(/(\s*| *)$/, "");
  12. }

68. 随机数时间戳

  1. function uniqueId() {
  2. var a = Math.random,
  3. b = parseInt;
  4. return (
  5. Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a())
  6. );
  7. }

69. 实现utf8解码

  1. function utf8_decode(str_data) {
  2. var tmp_arr = [],
  3. i = 0,
  4. ac = 0,
  5. c1 = 0,
  6. c2 = 0,
  7. c3 = 0;
  8. str_data += "";
  9. while (i < str_data.length) {
  10. c1 = str_data.charCodeAt(i);
  11. if (c1 < 128) {
  12. tmp_arr[ac++] = String.fromCharCode(c1);
  13. i++;
  14. } else if (c1 > 191 && c1 < 224) {
  15. c2 = str_data.charCodeAt(i + 1);
  16. tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
  17. i += 2;
  18. } else {
  19. c2 = str_data.charCodeAt(i + 1);
  20. c3 = str_data.charCodeAt(i + 2);
  21. tmp_arr[ac++] = String.fromCharCode(
  22. ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
  23. );
  24. i += 3;
  25. }
  26. }
  27. return tmp_arr.join("");
  28. }

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读

    相关 javascript函数

    javascript常用函数 javascript函数式编程,调用后,不修改原数据,返回运算后的新数组。 reduce 当提供了初始值时,初始值会放入第一次调用