JS Common Functions Daquan

Source: Internet
Author: User

Immune Bodyclick Method

This is a good method, a pop-up window, to be set in any other place click this window will automatically disappear, but the point of this window inside is OK. That's the way it's going to work.

(the part that produces immunity to the body click, blocks the bubbling Body event)//through ID mask-@args (event, Targetid) function Blockclicktobodybyid (A, b) {return b==$ ( A.target). Prop ("id") | | $ (a.target). Parents ("#" +b). length?! 1:!0}//through object masking, @args (event, target) function Blockclicktobodybyobj (A, b) {var c;return b=$ (c), B.prop ("id") | | (C=!0,b.prop ("id", "__kobe_special_id_zzzz__")), B.prop ("id") ==$ (A.target). Prop ("id") | | $ (a.target). Parents ("#" +b.prop ("id")). Length? (C&&b.removeattr ("id"),! 1):(c&&b.removeattr ("id"),!0)}//using if (false = = Blockclicktobodybyobj (EV, $ ("Div#test"))) return;//General Usage $ ("body"). On ("click", Function () {  if (false = = Blockclicktobodybyobj (EV, $ ("div#test"))) return;  $ ("#test"). Remove ();});
Convert URL parameter to obj
var urlparamtoobj = function (u) {  var sear = U.slice (U.indexof ("?") + 1). Split ("&"), p = {};  for (var i = 0, j=sear.length; j>i; i++) {    var s = sear[i].split ("=");    P[s[0]] = s[1];  }  return p;};
Array de-weight
Double for loop redo function Distinctarr (a) {var e,f,b=a.concat (), C=[],d=function (a,b,c) {var d;if (c) {for (d=b.length-1;d>= 0;d--) if (A===b[d]) return!0;return!1}for (d=b.length-1;d>=0;d--) if (A==b[d]) return!0;return!1};for (e= b.length-1;e>=0;e--) F=b.pop (), D (f,c) | | C.push (f); return c}//sorts the array and goes back to function Distinctandsortnumericarray (arr, wantdesc) {  var arrsorted = [], Sortdir =! Wantdesc? 1:-1;  Arr.sort (function (A, b) {    return (a) * WANTDESC;  });  For (Var i=0, j=arr.length, len2; j>i; i++) {    len2 = arrsorted.length;    if (len2) {      if (arrsorted[len2-1]! = arr[i])        Arrsorted.push (Arr[i]);    } else      Arrsorted.push (arr[i]);  }  return arrsorted;}
Cloning Method-clone ()
function Clone (obj) {  var o;  Switch (typeof obj) {case    ' undefined ': Break      ;    Case ' string ':      o = obj + ';      break;    Case ' number ':      o = obj-0;      break;    Case ' Boolean ':      o = obj;      break;    Case ' object ':      if (obj = = = null) {        o = null;      } else {        if (obj instanceof Array) {          o = [];          for (var i = 0, len = obj.length; i < Len; i++) {            O.push (Clone (Obj[i]));          }        } else {          o = {};          For (var k in obj) {            O[k] = Clone (Obj[k]);      }}} break;    Default:      o = obj;      break;  }  return o;}
Mailbox format-Regular check
var reemail =/^ (?: \ W+\.) *\[email protected]\w+ (?: \. \w+) +$/i;reemail.test ("[email protected]"),       //Truereemail.test ("[email protected]"),      //Falsereemail.test ("[Email protected]"),   //Truereemail.test ("[email protected]");    True
Generate GUID Code
Math.guid = function () {  return ' xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx '. Replace (/[xy]/g, function (c) {    var r = Math.random () *16|0, v = c = = "X"? R: (r&0x3|0x8);    return v.tostring (+);  }). toUpperCase ();};
Random generation of alphanumeric strings (CAPTCHA)
function Generaterandomalphanum (len) {  var rdmstring = "";  for (; rdmstring.length < Len; rdmstring  + = Math.random (). toString (. substr (2));  return  rdmstring.substr (0, Len);} Translator Note: specifically checked math.random () generates a random number from 0 to 1, number.tostring (36) Converts this number to 36 binary (0-9,a-z), and finally substr removes the previous "0." String
Base64 string encoding and decoding
function Base64Encode (str) {  return Btoa (unescape (encodeURIComponent (str)));} function Base64decode (str) {  return decodeuricomponent (Escape (Atob (str)));
JS compatible get final style
function GetStyle (obj, attribute) {  return obj.currentstyle? Obj.currentstyle[attribute]: Document.defaultView.getComputedStyle (obj, null) [attribute];} Ie:var bgColor = ODiv.currentStyle.backgroundColor; Read-only, if you write to it error//dom://getcomputedstyle (obj,null) accepts two parameters, requires a STYLE element and a pseudo-element such as: hover and: first-letter var bgColor = Document.defaultView.getComputedStyle (Odiv, null). BackgroundColor;
Large numbers add commas every 3 bits
function Addcommas (nstr) {  nstr + = ';  var x = Nstr.split ('. ');  var x1 = x[0];  var x2 = x.length >; 1? '. ' + x[1]: ';  var rgx =/(d+) (d{3})/;  while (Rgx.test (x1)) {    x1 = x1.replace (RGX, ' $ ' + ', ' + ' $ ');  }  return x1 + x2;}
Window.requestanimationframe compatible notation
Window.requestanimframe = function () {  return Window.requestanimationframe | | window.webkitrequestanimationframe || Window.mozrequestanimationframe | | Window.orequestanimationframe | | Window.msrequestanimationframe | | function (E, t) {    return window.settimeout (E, 1e3/60)  };} ();
JS Trim ()
s = new String ("   --Kobe  "). Trim ()-  -Kobe "s = new String ("   --Kobe  "). Trimleft ()--Kob E  "s = new String ("   --Kobe  "). TrimRight (),"   --Kobe "//Regular implementation trim () function trim (a) {return a.rep Lace (/(^\s*) | ( \s*$)/g, "")}//Jquery$.trim ("haha");
Determine browser type
Browser judgment, use method: var useragent = navigator.userAgent.toLowerCase (); browser = {  version: (Useragent.match (/.+) (?: Rv|it |ra|ie) [\/:] ([\d.] +)/) || [0, ' 0 ']) [1],  Safari:/webkit/.test (useragent),  Opera:/opera/.test (useragent),  Chrome:/chrome/.test ( useragent),  msie:/msie/.test (useragent) &&!/opera/.test (useragent),  Mozilla:/mozilla/.test ( useragent) &&!/(Compatible|webkit)/.test (useragent)}//Judge Ie6function IsIe6 () {  if (Browser.msie & & browser.version = = ' 6.0 ') {    alert (' He is IE6 ');  } else {    alert (' Not IE6 ');}  } IsIe6 ();

jquery Method:

/* <! [cdata[*/$ (document). Ready (function () {  var bro = $.browser;  var binfo = "";  if (Bro.msie) {    binfo = "Microsoft Internet Explorer" + bro.version;  }  if (Bro.mozilla) {    binfo = "Mozilla Firefox" + bro.version;  }  if (Bro.safari) {    binfo = "Apple Safari" + bro.version;  }  if (Bro.opera) {    binfo = "Opera" + Bro.version;  }  alert (binfo);  $ ("#browser"). HTML (binfo);}) /*]]> */
Get the browser prefix
var prefix = (function () {  if ("undefined"!== typeof window.getComputedStyle) {    var styles = Window.getcomputedst YLE (Document.documentelement, "),      pre = (Array.prototype.slice        . Call (Styles)        . Join (')        . Match (/- (moz|webkit|ms)-/) | | (Styles. Olink = = = ' && [', ' O '])      [1],      dom = (' webkit| moz|ms| O '). Match (New RegExp (' (' + pre + ') ', ' I ')) [1];    return {      dom:dom,      lowercase:pre,      css: '-' + pre + '-',      js:pre[0].touppercase () + pre.substr (1) 
   
    };  }}) ();
   

The output is:

{"Dom": "WebKit", "lowercase": "WebKit", "CSS": "-webkit-", "JS": "WebKit"} {"Dom": "MS", "lowercase": "MS", "CSS": "-ms-", "JS": "MS"} {"Dom": "Moz", "lowercase": "Moz", "CSS": "-moz-", "JS": "Moz"}
Throttle-debounce
/* * Frequency Control returns the function that the FN execution frequency is limited to execute once per time * @param fn {function} needs to be called @param delay {Number} delay time, per millisecond * @param IMM The function that ediate {bool} passes a false binding to the immediate parameter executes first, not after delay.    * @return {function} is actually called */var throttle = functions (FN, delay, immediate, debounce) {var curr = +new Date (),//Current time      Last_call = 0, last_exec = 0, timer = null, diff,//Time difference context,//context args, exec = function () {      Last_exec = Curr;    Fn.apply (context, args);  };    return function () {Curr = +new Date ();    context = this, args = arguments, diff = curr-(debounce? last_call:last_exec)-delay;    Cleartimeout (timer);      if (debounce) {if (immediate) {timer = SetTimeout (exec, delay);      } else if (diff >= 0) {exec ();      }} else {if (diff >= 0) {exec ();      } else if (immediate) {timer = SetTimeout (exec,-diff);  }} last_call = Curr; }};/* * Idle control return function Continuous call, idle time must be greater than or equal to DELAY,FN to execute * @param fn{function} functions to be called * @param delay {Number} idle time * @param immediate {bool} The function passed false to the immediate parameter is executed first, not after delay 。 * @return {function} is actually called */var debounce = functions (FN, delay, immediate) {return throttle (FN, delay, immediate, Tru e);};/      /package deferred execution function $.event.special.throttledscroll = {setup:function (data) {var timer = 0) through the combination of special events and custom events for jquery            $ (this). bind (' Scroll.throttledscroll ', function (event) {if (!timer) {timer = SetTimeout (function () {            $ (this). Triggerhandler (' Throttledscroll ');          Timer = 0;        }, 250);    }      });    }, Teardown:function () {$ (this). Unbind (' Scroll.throttledscroll '); }  };}) (jQuery); $ (document). Ready (function () {$window. bind (' Throttledscroll ', checkscrollposition). Trigger (' Throttledscroll ');});
Get the pseudo-elements of CSS

:hover, :active ,..... :before

var bgcolor = window.getComputedStyle (    document.queryselector ('. Element '), ': Before '). GetPropertyValue (' Background-color ') var afontsize = window.getComputedStyle (document.getElementById ("a"), ": hover"). FontSize;
JS type judgment
    • typeof: obj, NULL, arr, RegExp, and custom objects are not well judged

    • constructor: Supports most object type judgments, especially custom type objects, but cannot be used on null and undefined

    • String.prototype.toString.call(): Supports most types of judgments, but does not support custom type objects

      var toString = Object.prototype.toString;
      Console.log (Tostring.call (arr)); [Object Array]
      Console.log (Tostring.call (nullobj)); [Object Null]
      Console.log (Tostring.call (user)); [Object Object] cannot be further judged

      Why not just use obj.tostring ()? Because Obj.tostring () returns the contents of its object, such as values, strings, arrays, etc., it is not good to judge

Summary : Recommended use Object.prototype.toString.call() , because he can solve most of the situation of the judgment, when the return value is encountered [object Object] , then use the constructor auxiliary judgment to see whether it is a custom object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.