This is the 7th day of my participation in the August Text Challenge.More challenges in August

Escape HTML tags

function HtmlEncode(text) {
  return text
    .replace(/&/g."&")
    .replace(/\"/g.'"')
    .replace(/</g."<")
    .replace(/>/g.">");
}
Copy the code

HTML tag escape

// HTML tags escape
// @param {Array.
      
       } templateData tokens of string type
      
// @param {... }.. Tokens for the vals placeholder
//
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."&")
      .replace(/</g."<")
      .replace(/>/g.">");
    // Don't escape special characters in the template.
    s += templateData[i];
  }
  return s;
}
/ / call
var html = SaferHTMLThis is an introduction to string templates 

Copy the code

Add the on method to the element

Element.prototype.on = Element.prototype.addEventListener;
NodeList.prototype.on = function (event, fn) {, [] ['forEach'].call(this.function (el) {
        el.on(event, fn);
    });
    return this;
};
Copy the code

Add the trigger method to the element

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;
};
Copy the code

Bind events across browsers

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; }}Copy the code

Add to favorites

function addFavorite(sURL, sTitle) {
  try {
    window.external.addFavorite(sURL, sTitle);
  } catch (e) {
    try {
      window.sidebar.addPanel(sTitle, sURL, "");
    } catch (e) {
      alert("Failed to add favorites, please use Ctrl+D to add."); }}}Copy the code

Extract all urls from the page code

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

Load script files dynamically

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) {}
}
Copy the code

Returns the generic method at the top

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");
Copy the code

Implement base64 decoding

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;
}
Copy the code

Verify whether the keyboard is a valid input value

function checkKey(iKey) {
  if (iKey == 32 || iKey == 229) {
    return true;
  } /* Whitespace and exception */
  if (iKey > 47 && iKey < 58) {
    return true;
  } / * * / number
  if (iKey > 64 && iKey < 91) {
    return true;
  } * / / * letters
  if (iKey > 95 && iKey < 108) {
    return true;
  } /* Numeric keypad 1*/
  if (iKey > 108 && iKey < 112) {
    return true;
  } /* Numeric keypad 2*/
  if (iKey > 185 && iKey < 193) {
    return true;
  } / * 1 * / symbols
  if (iKey > 218 && iKey < 223) {
    return true;
  } / * 2 * / symbols
  return false;
}
Copy the code

Full Angle and half Angle conversion

//iCase: 0 all to half, 1 half to all, other not converted
function chgCase(sStr, iCase) {
  if (
    typeofsStr ! ="string" ||
    sStr.length <= 0| |! (iCase ===0 || iCase == 1)) {return sStr;
  }
  var i,
    oRs = [],
    iCode;
  if (iCase) {
    /* half -> full */
    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 {
    /* full -> half */
    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("");
}
Copy the code

Version of the contrast

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;
}
Copy the code

Compress the CSS style code

function compressCss(s) {
  // Compress the code
  s = s.replace(/\/\*(.|\n)*? \*\//g.""); // Delete comments
  s = s.replace(/\s*([\{\}\:\;\,])\s*/g."$1");
  s = s.replace(/\,[\s\.\#\d]*\{/g."{"); // error tolerance
  s = s.replace(/; \s*; /g.";"); // Clear consecutive semicolons
  s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); // Remove the first and last whitespace
  return s == null ? "" : s[1];
}
Copy the code

Get the current path

var currentPageUrl = "";
if (typeof this.href === "undefined") {
  currentPageUrl = document.location.toString().toLowerCase();
} else {
  currentPageUrl = this.href.toString().toLowerCase();
}
Copy the code

String length interception

function cutstr(str, len) {
    var temp,
        icount = 0,
        patrn = /[^\x00-\xff]/The 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 + "..."
}
Copy the code

Time and date format conversion

Date.prototype.format = function(formatStr) {
  var str = formatStr;
  var Week = ["Day"."一"."二"."Three"."Four"."Five"."Six"];
  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;
};

/ / or
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"));
Copy the code

Delete events across browsers

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; }}Copy the code

Determines whether to end with a string

String.prototype.endWith = function(s) {
  var d = this.length - s.length;
  return d >= 0 && this.lastIndexOf(s) == d;
};
Copy the code

Return script content

function evalscript(s) {
  if (s.indexOf("<script") = = -1) return s;
  var p = /
      [^\>;
  var arr = [];
  while ((arr = p.exec(s))) {
    var p1 = /
      [^\>;
    var arr1 = [];
    arr1 = p1.exec(arr[0]);
    if (arr1) {
      appendscript(arr1[1]."", arr1[2], arr1[3]);
    } else {
      p1 = /
      (.*?)>;
      arr1 = p1.exec(arr[0]);
      appendscript("", arr1[2], arr1[1].indexOf("reload=") != -1); }}return s;
}
Copy the code

Format the CSS style code

function formatCss(s) {
  // Format the code
  s = s.replace(/\s*([\{\}\:\;\,])\s*/g."$1");
  s = s.replace(/; \s*; /g.";"); // Clear consecutive semicolons
  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;
}
Copy the code

Get the cookie value

function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "= (/ ^; (*). | $)"));
  if(arr ! =null) return unescape(arr[2]);
  return null;
}
Copy the code

Gets the value of the GET parameter in the URL

// If the address is test.htm? T1 & t2 = = 1, 2 & t3 = 3, then can obtain: GET (" t1 "), GET (" t2 "), the GET/" t3 "function getGet () {querystr = window. The location. The 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]; }Copy the code

Gets the mobile device initialization size

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;
}
Copy the code

Get page height

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);
}
Copy the code

Get the page scrollLeft

function getPageScrollLeft() {
  var a = document;
  return a.documentElement.scrollLeft || a.body.scrollLeft;
}
Copy the code

Get the page scrollTop

function getPageScrollTop() {
  var a = document;
  return a.documentElement.scrollTop || a.body.scrollTop;
}
Copy the code

Gets the page viewable height

function getPageViewHeight() {
  var d = document,
    a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  return a.clientHeight;
}
Copy the code

Gets the page visible width

function getPageViewWidth() {
  var d = document,
    a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  return a.clientWidth;
}
Copy the code

Get page width

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);
}
Copy the code

Gets the mobile device screen width

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;
}
Copy the code

Gets the location to which the page is rolled

function getScrollXY() {
  return document.body.scrollTop
    ? {
        x: document.body.scrollLeft,
        y: document.body.scrollTop
      }
    : {
        x: document.documentElement.scrollLeft,
        y: document.documentElement.scrollTop
      };
}
Copy the code

Gets the parameters on the URL

// Get the value of a parameter in the URL, case insensitive
// Get the value of a parameter in the URL, case insensitive,
// The default is to take the arguments in 'hash',
// If other parameters are passed, the parameter in 'search' is supported
// @param {String} name Parameter 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;
}
Copy the code

Verify that the URL link is valid

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; }}}Copy the code

Gets the width and height of a form’s visible range

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);
}
Copy the code

Get maximum size of mobile device

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; }}Copy the code

Check whether android mobile device access

function isAndroidMobileDevice() {
  return /android/i.test(navigator.userAgent.toLowerCase());
}
Copy the code

Determine whether apple mobile device access

function isAppleMobileDevice() {
  return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());
}
Copy the code

Check whether the value is a number

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

Is it a certain type of phone

// Use devicePixelRatio and resolution
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;
};
Copy the code

Check whether the device is moved

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;
}
Copy the code

Is it a cell phone number

function isMobileNumber(e) {
  var i =
      "134135136137138139150151152157158159187188147182183184178",
    n = "130131132155156185186145176",
    a = "133153180181189177173170",
    o = e || "",
    r = o.substring(0.3),
    d = o.substring(0.4),
    s =
      !!/^1\d{10}$/.test(o) &&
      (n.indexOf(r) >= 0
        ? "China unicom"
        : a.indexOf(r) >= 0
        ? "Telecommunications"
        : "1349" == d
        ? "Telecommunications"
        : i.indexOf(r) >= 0
        ? "Mobile"
        : "Unknown");
  return s;
}
Copy the code

Check whether it is accessed from a mobile device

function isMobileUserAgent() {
  return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(
    window.navigator.userAgent.toLowerCase()
  );
}
Copy the code

Determines whether the mouse moves out of the event

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; }returnreltg ! == handler; }Copy the code

Check whether to Touch the screen

function isTouchScreen() {
  return (
    "ontouchstart" in window| | -window.DocumentTouch && document instanceof DocumentTouch)
  );
}
Copy the code

Check whether it is a web address

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; }}Copy the code

Determine whether to open Windows

function isViewportOpen() {
  return!!!!!document.getElementById("wixMobileViewport");
}
Copy the code

Loading style file

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); }}Copy the code

Replace address bar

function locationReplace(url) {
  if (history.replaceState) {
    history.replaceState(null.document.title, url);
    history.go(0);
  } else{ location.replace(url); }}Copy the code

Resolve offsetX compatibility issues

// offsetX/Y is not supported for Firefox
function getOffset(e) {
  var target = e.target, // The target object of the current trigger
    eventCoord,
    pageCoord,
    offsetCoord;

  // Calculates the distance between the current triggering element and the document
  pageCoord = getPageCoord(target);

  // Calculate the distance between the cursor and the document
  eventCoord = {
    X: window.pageXOffset + e.clientX,
    Y: window.pageYOffset + e.clientY
  };

  // Subtract the coordinates of the cursor to the first positioned parent element
  offsetCoord = {
    X: eventCoord.X - pageCoord.X,
    Y: eventCoord.Y - pageCoord.Y
  };
  return offsetCoord;
}

function getPageCoord(element) {
  var coord = { X: 0.Y: 0 };
  // Count from the current triggering element to the root node,
  // Sum of offsetLeft or offsetTop values of each offsetParent element
  while (element) {
    coord.X += element.offsetLeft;
    coord.Y += element.offsetTop;
    element = element.offsetParent;
  }
  return coord;
}
Copy the code

Open a form generic method

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(); }}Copy the code

Concatenate key-value pairs into URL strip parameters

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('&'))}Copy the code

Remove url prefix

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;
}
Copy the code

Replace all

String.prototype.replaceAll = function(s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2); }; The operation of copying code resizefunction() {
  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) {
      // Perform the operation when the width of the window is less than 1255
    } else {
      // Perform the operation when the width of the window is greater than 1255}};if (window.addEventListener) {
    window.addEventListener("resize".function() {
      fn();
    });
  } else if (window.attachEvent) {
    window.attachEvent("onresize".function() { fn(); }); } fn(); }) ();Copy the code

Scroll to the top

/ / use the document. The documentElement. ScrollTop or document. The body. The scrollTop distance to get to the top, from the top
// Scroll a small distance. Use Windows. RequestAnimationFrame () to scroll.
// @example
// scrollToTop();
function scrollToTop() {
  var c = document.documentElement.scrollTop || document.body.scrollTop;

  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8); }}Copy the code

Set the cookie value

function setCookie(name, value, Hours) {
  var d = new Date(a);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;";
}
Copy the code

Set to the home page

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(
          "This operation is rejected by the browser. To enable this function, enter about:config in the address box and set the signed.applets.codebase_principal_support value to true."); }}var prefs = Components.classes[
      "@mozilla.org/preferences-service; 1"
    ].getService(Components.interfaces.nsIPrefBranch);
    prefs.setCharPref("browser.startup.homepage"."http://w3cboy.com"); }}Copy the code

Sort each row alphabetically by array sort

function setSort() {
  var text = K1.value
    .split(/[\r\n]/)
    .sort()
    .join("\r\n"); / / order
  var test = K1.value
    .split(/[\r\n]/)
    .sort()
    .reverse()
    .join("\r\n"); / / orderK1.value = K1.value ! = text ? text : test; }Copy the code

Delay to perform

// For example sleep(1000) means to wait 1000 milliseconds and can be implemented from Promise, Generator, Async/Await, etc.
// 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);
Copy the code

Determines whether to start with a string

String.prototype.startWith = function(s) {
  return this.indexOf(s) == 0;
};
Copy the code

Clearing script content

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

Time personalized output function

< 60s, "just" is displayed. 2, >= 1min && < 60min, "XX minutes ago" is displayed. 3, >= 60min && < 1day, 4, >= 1day && < 1year, displays the date "XX month XX day XX:XX" 5, >= 1year, displays the specific date "XXXX month XX day 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 + "Year" + month + "Month" + day + "Day" + hour + ":" + minute;
  } else {
    var pastTime = curDate - date,
      pastH = pastTime / 3600000;

    if (pastH > curHour) {
      timeStr = month + "Month" + day + "Day" + hour + ":" + minute;
    } else if (pastH >= 1) {
      timeStr = "Today" + hour + ":" + minute + "Points";
    } else {
      var pastM = curDate.getMinutes() - minute;
      if (pastM > 1) {
        timeStr = pastM + "Minutes ago.";
      } else {
        timeStr = "Just"; }}}return timeStr;
}
Copy the code

Full Angle is converted to half Angle function

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;
}
Copy the code

Half Angle is converted to full Angle function

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;
}
Copy the code

Amount uppercase conversion function

function transform(tranvalue) {
  try {
    var i = 1;
    var dw2 = new Array(""."万"."亿"); / / the big unit
    var dw1 = new Array("Pick up"."Hk"."仟"); / / small units
    var dw = new Array(
      "Zero"."One"."贰"."叁"."Boss"."Wu"."Lu"."Pure".""."Nine"
    ); 
    // Use the integer part
    // The following conversion from lowercase to uppercase is displayed in the total uppercase text box
    // Separate integers from decimals
    var source = splits(tranvalue);
    var num = source[0];
    var dig = source[1];
    // Convert the integer part
    var k1 = 0; // Small units
    var k2 = 0; // The unit is large
    var sum = 0;
    var str = "";
    var len = source[0].length; // Integer length
    for (i = 1; i <= len; i++) {
      var n = source[0].charAt(len - i); // Get the number of a certain digit
      var bn = 0;
      if (len - i - 1> =0) {
        bn = source[0].charAt(len - i - 1); // Get the digit preceding the digit
      }
      sum = sum + Number(n);
      if(sum ! =0) {
        str = dw[Number(n)].concat(str); // Get the corresponding uppercase number and insert it before the STR string
        if (n == "0") sum = 0;
      }
      if (len - i - 1> =0) {
        // Within the range of numbers
        if(k1 ! =3) {
          // Add small units
          if(bn ! =0) {
            str = dw1[k1].concat(str);
          }
          k1++;
        } else {
          // Instead of adding small units, increase units
          k1 = 0;
          var temp = str.charAt(0);
          if (temp == "万" || temp == "亿")
            // If there is no number before the larger unit, omit the larger unit
            str = str.substr(1, str.length - 1);
          str = dw2[k2].concat(str);
          sum = 0; }}if (k1 == 3) {
        // If a small unit goes up to a thousand, a large unit goes up to onek2++; }}// Convert the decimal part
    var strdig = "";
    if(dig ! ="") {
      var n = dig.charAt(0);
      if(n ! =0) {
        strdig += dw[Number(n)] + "Angle"; / / add Numbers
      }
      var n = dig.charAt(1);
      if(n ! =0) {
        strdig += dw[Number(n)] + "Points"; / / add Numbers
      }
    }
    str += "Yuan" + strdig;
  } catch (e) {
    return "0 yuan";
  }
  return str;
}
// Split integers and decimals
function splits(tranvalue) {
  var value = new Array(""."");
  temp = tranvalue.split(".");
  for (var i = 0; i < temp.length; i++) {
    value = temp;
  }
  return value;
}
Copy the code

Remove the blank space

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

// Clear the left space
function ltrim(s) {
  return s.replace(/ ^ (\ | s * *) /."");
}

// Clear the right space
function rtrim(s) {
  return s.replace(/ $/ (\ | s * *)."");
}
Copy the code

Random number timestamp

function uniqueId() {
  var a = Math.random,
    b = parseInt;
  return (
    Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a())
  );
}
Copy the code

Utf8 decoding

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("");
}
Copy the code