DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 常用Javascript函數與原型功能收藏(必看篇)
常用Javascript函數與原型功能收藏(必看篇)
編輯:關於JavaScript     

如下所示:

// 重復字符串
String.prototype.repeat = function(n) {
  return new Array(n+1).join(this);
}
 
// 替換全部
String.prototype.replaceAll = function(str1, str2) {
  return this.replace(new RegExp(str1, "gm"), str2);
}
 
// 清除空格
String.prototype.trim = function() {
  return this.replace(/^\s*(.*?)\s+$/, "$1");
}
 
// 計算數組中的最大值
Array.prototype.max = function() {
  return Math.max.apply({}, this);
}
 
// 計算數組中的最小值
Array.prototype.min = function() {
  return Math.min.apply({}, this);
}
 
// 復制數組
Array.prototype.copy = function() {
  return [].concat(this);
};
 
// 去除數組中指定元素,只能去除一個,如果想多個,之前先用unique處理
Array.prototype.remove = function(value){
  for (var i = 0, len = this.length; i < len; i++) {
    if (this[i] == value) {
      this.splice(i, 1);
      break;
    }
  }
  return this;
}
 
// 判斷數組中是否存在指定元素,返回索引值
Array.prototype.inArray = function(value) {
  var index = -1, key;
  for (key in this) {
    if (this[key] == value) {
      index = key;
      break;
    }
  }
  return index;
}
 
// 去除數組中的重復元素
Array.prototype.unique = function() {
  var key, ret = [];
  for (key in this) {
    if (ret.inArray(this[key]) < 0) {
      ret.push(this[key]);
    }
  }
  return ret;
}
 
// 檢測是否已經安裝flash,檢測flash的版本
var flashVersion = (function() {
  var version;
  try {
    version = navigator.plugins['Shockwave Flash'];
    version = version.description;
  } catch (ex) {
    try {
      version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
        .GetVariable('$version');
    } catch (ex2) {
      version = '0.0';
    }
  }
  version = version.match(/\d+/g);
  return parseFloat(version[0] + '.' + version[1], 10);
})();
 
// 檢測是否支持transition
var supportTransition = (function() {
  var s = document.createElement('p').style,
    r = 'transition' in s ||
    'WebkitTransition' in s ||
    'MozTransition' in s ||
    'msTransition' in s ||
    'OTransition' in s;
  s = null;
  return r;
})();
 
// 判斷浏覽器是否支持圖片的base64
var isSupportBase64 = (function() {
  var data = new Image();
  var support = true;
  data.onload = data.onerror = function() {
    if (this.width != 1 || this.height != 1) {
      support = false;
    }
    return support;
  };
  data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
})();
 
// 首字母大寫
function ucfirst(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
 
// 清除左空格
function ltrim(str) {
  return str.replace(/^(\s*| *)/, "");
}
 
// 清除右空格
function rtrim(str) {
  return str.replace(/(\s*| *)$/, "");
}
 
// 設置Cookie值
function setCookie(name, value, hours, path, domain) {
  var d = new Date();
  var offset = 8;
  var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  var nd = utc + (3600000 * offset);
  var expire = new Date(nd);
  expire.setTime(expire.getTime() + hours * 60 * 60 * 1000);
  var path = path || "";
  var domain = domain || "";
  document.cookie = name + "=" + escape(value) + ";path="+ path +";expires=" + expire.toGMTString() + ";domain="+ domain +";"
}
 
// 獲取Cookie值
function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) {
    return unescape(arr[2]);
  }
  return null;
}
 
// 刪除Cookie值
function removeCookie(name) {
  setCookie(name, "", -1);
}
 
// 生成范圍隨機數
function rand(n, m) {
  return Math.random() * (m - n) + n;
}
 
// 加入收藏夾
function addFavorite(url, title) {
  try {
    window.external.addFavorite(url, title);
  } catch(e) {
    try {
      window.sidebar.addPanel(title, url, "");
    } catch(e) {
      alert("加入收藏失敗,請使用Ctrl+D進行添加");
    }
  }
}
 
// 設為首頁
function setHomepage(url) {
  if (document.all) {
    document.body.style.behavior = 'url(#default#homepage)';
    document.body.setHomePage(url);
  } 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', url);
  }
}
 
// 加載樣式文件
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 stripscript(str) {
  return str.replace(/<script.*?>.*?<\/script>/ig, '');
}
 
// 檢驗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;
    }
  }
}
 
// 格式化CSS代碼
function formatCss(str){
  str = str.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
  str = str.replace(/;\s*;/g, ";"); //清除連續分號
  str = str.replace(/\,[\s\.\#\d]*{/g, "{");
  str = str.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2");
  str = str.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2");
  str = str.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2");
  return str;
}
 
// 壓縮CSS代碼
function compressCss (str) {
  str = str.replace(/\/\*(.|\n)*?\*\//g, "");    //刪除注釋
  str = str.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
  str = str.replace(/\,[\s\.\#\d]*\{/g, "{");    //容錯處理
  str = str.replace(/;\s*;/g, ";");         //清除連續分號
  str = str.match(/^\s*(\S+(\s+\S+)*)\s*$/);    //去掉首尾空白
  return (str == null) ? "" : s[1];
}
 
// getElementsByClassName
function getElementsByClassName(name, context) {
  var context = context || document;
  if (context.getElementsByClassName) {
    return context.getElementsByClassName(name);
  }
   
  var nodes = context.getElementsByTagName("*"), nodesLength = nodes.length, ret = [];
  for (var i = 0; i < nodesLength; i++) {
    var className = nodes[i].className;
    if (nodes[i].nodeType == 1 && className) {
      var classes = className.split(' ');
      for (var j = 0; j < classes.length; j++) {
        if (name == classes[j]) {
          ret.push(nodes[i]);
          break
        }
      }
    }
  }
  return ret;
}
 
// 獲取頁面高度
function getPageHeight() {
  var doc = document;
  var rot = doc.compatMode == "BackCompat" ? doc.body : doc.documentElement;
  return Math.max(doc.documentElement.scrollHeight, doc.body.scrollHeight, rot.clientHeight);
}
 
// 獲取頁面scrollLeft
function getPageScrollLeft() {
  var doc = document;
  return doc.documentElement.scrollLeft || doc.body.scrollLeft;
}
 
// 獲取頁面可視寬度
function getPageViewWidth() {
  var doc = document;
  var rot = doc.compatMode == "BackCompat" ? doc.body : doc.documentElement;
  return rot.clientWidth;
}
 
// 獲取頁面寬度
function getPageWidth(){
  var doc = document;
  var rot = doc.compatMode == "BackCompat" ? doc.body : doc.documentElement;
  return Math.max(doc.documentElement.scrollWidth, doc.body.scrollWidth, rot.clientWidth);
}
 
// 獲取頁面scrollTop
function getPageScrollTop(){
  var doc = document;
  return doc.documentElement.scrollTop || doc.body.scrollTop;
}
 
// 獲取頁面可視高度
function getPageViewHeight() {
  var doc = document;
  var rot = doc.compatMode == "BackCompat" ? doc.body : doc.documentElement;
  return rot.clientHeight;
}
 
// 獲取網頁被卷去的位置
function getScrollXY() {
  return document.body.scrollTop ? {
    x : document.body.scrollLeft,
    y : document.body.scrollTop
  } : {
    x : document.documentElement.scrollLeft,
    y : document.documentElement.scrollTop
  }
}
// 獲取元素的樣式值
function getStyle(elem, name) {
  if (elem.style[name]) {
    return elem.style[name];
  } else if (elem.currentStyle) {
    return elem.currentStyle[name];
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
    var s = document.defaultView.getComputedStyle(elem, "");
    return s && s.getPropertyValue(name);
  } else {
    return null;
  }
}
 
// 獲取元素相對於這個頁面的X坐標
function pageX(elem) {
  return elem.offsetParent ? (elem.offsetLeft + pageX(elem.offsetParent)) : elem.offsetLeft;
}
 
// 獲取元素相對於這個頁面的Y坐標
function pageY(elem) {
  return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}
 
// 獲取元素相對於父元素的X坐標
function parentX(elem) {
  return elem.parentNode == elem.offsetParent ? elem.offsetLeft : pageX(elem) - pageX(elem.parentNode);
}
 
// 獲取元素相對於父元素的Y坐標
function parentY(elem) {
  return elem.parentNode == elem.offsetParent ? elem.offsetTop : pageY(elem)-pageY(elem.parentNode);
}
 
// 獲取使用CSS定位的元素的X坐標
function posX(elem) {
  return parseInt(getStyle(elem, "left"));
}
 
// 獲取使用CSS定位的元素的Y坐標
function posY(elem) {
  return parseInt(getStyle(elem, "top"));
}
 
// 設置元素X位置
function setX(elem, pos) {
  elem.style.left = pos + "px";
}
 
// 設置元素Y位置
function setY(elem, pos) {
  elem.style.top = pos + "px";
}
 
// 增加元素X坐標
function addX(elem, pos) {
  set(elem, (posX(elem) + pos));
}
 
// 增加元素Y坐標
function addY(elem, pos) {
  set(elem, (posY(elem) + pos));
}
 
// 獲取元素使用CSS控制大小的高度
function getHeight(elem) {
  return parseInt(getStyle(elem, "height"));
}
 
// 獲取元素使用CSS控制大小的寬度
function getWidth(elem) {
  return parseInt(getStyle(elem, "width"));
}
 
// 設置透明度
function setOpacity(elem, num) {
  if (elem.filters) {
    elem.style.filter="alpha(opacity="+ num +")";
  } else {
    elem.style.opacity = num/100;
  }
}
 
// 獲取鼠標光標相對於整個頁面的X位置
function getX(e) {
  e = e || window.event;
  return e.pageX || e.clientX + document.body.scrollLeft;
}
 
// 獲取鼠標光標相對於整個頁面的Y位置
function getY(e) {
  e = e || window.event;
  return e.pageY || e.clientY + document.body.scrollTop;
}
 
// 獲取鼠標光標相對於當前元素的X位置
function getElementX(e) {
  return (e && e.layerX) || window.event.offsetX;
}
 
// 獲取鼠標光標相對於當前元素的Y位置
function getElementY(e) {
  return (e && e.layerY) || window.event.offsetY;
}
 
// 獲取滾動條的X位置
function scrollX() {
  var de = document.documentElement;
  return self.pageXOffset || (de && de.scrollLeft) || document.body.scrollLeft;
}
 
// 獲取滾動條的Y位置
function scrollY() {
  var de = document.documentElement;
  return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;
}
 
// 確認是否鍵盤有效輸入值
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;
}
 
// 獲得URL中GET參數值
function getParams() {
  var queryStr = window.location.href.split("?");
  var params = [];
  if (queryStr[1]) {
    var gets = queryStr[1].split("&");
    for (var i = 0; i < gets.length; i++) {
      temp = gets.split("=");
      params[temp[0]] = temp[1];
    }
  }
  return params;
}
 
// 字符串反序
function strReverse(text) {
  return text.split('').reverse().join('');
}
 
// HTML實體
function htmlEncode(str) {
  var s = "";
  if (str.length == 0) return "";
  s = str.replace(/\&/g, "&");
  s = s.replace(/</g, "<");
  s = s.replace(/>/g, ">");
  s = s.replace(/\'/g, "'");
  s = s.replace(/\"/g, "&qout;");
  return s;
}
 
// HTML還原
function htmlDecode(str) {
  var s = "";
  if (str.length == 0) return "";
  s = str.replace(/&/g, "&");
  s = s.replace(/</g, "<");
  s = s.replace(/>/g, ">");
  s = s.replace(/'/g, "\'");
  s = s.replace(/&qout;/g, "\"");
  return s;
}
 
// 克隆
function clone(obj) {
  var ret;
  switch (typeof obj) {
    case 'undefined':
      break;
    case 'string':
      ret = obj + '';
      break;
    case 'number':
      ret = obj - 0;
      break;
    case 'boolean':
      ret = obj;
      break;
    case 'object':
      if (obj === null) {
        ret = null;
      } else {
        if (obj instanceof Array) {
          ret = [];
          for (var i = 0, len = obj.length; i < len; i++) {
            ret.push(clone(obj[i]));
          }
        } else {
          ret = {};
          for (var k in obj) {
            ret[k] = clone(obj[k]);
          }
        }
      }
      break;
    default:
      ret = obj;
      break;
  }
  return ret;
}
 
// 檢測變量是否為email格式
function isEmail(mail) {
  if (/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(mail)) {
    return true;
  }
  return false;
}
 
// 驗證身份證號碼
function isIdenCode(code){
  var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"內蒙古",21:"遼寧",22:"吉林",23:"黑龍江 ",31:"上海",32:"江蘇",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山東",41:"河南",42:"湖北 ",43:"湖南",44:"廣東",45:"廣西",46:"海南",50:"重慶",51:"四川",52:"貴州",53:"雲南",54:"西藏 ",61:"陝西",62:"甘肅",63:"青海",64:"寧夏",65:"新疆",71:"台灣",81:"香港",82:"澳門",91:"國外"};
  var tip = "";
  var pass = true;
  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = "身份證號格式錯誤";
    pass = false;
  } else if (!city[code.substr(0,2)]) {
    tip = "地址編碼錯誤";
    pass = false;
  } else {
    //18位身份證需要驗證最後一位校驗位
    if(code.length == 18){
      code = code.split('');
      //∑(ai×Wi)(mod 11)
      //加權因子
      var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
      //校驗位
      var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
       
      var last = parity[sum % 11];
      if (parity[sum % 11] != code[17]) {
        tip = "校驗位錯誤";
        pass = false;
      }
    }
  }
  return pass;
}
 
// 檢測變量是否為小數
function isDecimal(dec){
  if (dec.match(/^-?\d+(\.\d+)?$/g) == null) {
    return false;
  }
  return true;
}
 
// 檢測變量是否為整型
function isInteger(num){
  if (num.match(/^[-+]?\d*$/) == null) {
    return false;
  }
  return true;
}
 
// 檢測變量是否為時間格式
function checkTime(str) {
  var time = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
  if (time == null) {
    return false;
  }
   
  if (time[1] > 24 || time[3] > 60 || time[4] > 60) {
    return false
  }
  return true;
}
 
// 檢測變量類型是否為日期格式
function checkDate(str) {
  var date = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  if (date == null) {
    return false;
  }
   
  var d = new Date(r[1], r[3]-1, r[4]);
  return (d.getFullYear() == r[1] && (d.getMonth()+1) == r[3] && d.getDate() == r[4]);
}
 
// 檢測變量是否為長日期格式
function checkDateTime(str) {
  var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
  var dt = str.match(reg);
  if (dt == null) {
    return false;
  }
   
  var d = new Date(dt[1], dt[3]-1, dt[4], dt[5], dt[6], dt[7]);
  return (d.getFullYear() == dt[1] && (d.getMonth()+1) == dt[3] && d.getDate() == dt[4] && d.getHours() == dt[5] && d.getMinutes() == dt[6] && d.getSeconds() == dt[7]);
}
 
// 檢測變量是否為未定義
function isUndefined(val) {
  return typeof val === 'undefined';
}
 
// 檢測變量是否為定義
function isDefined(val) {
  return typeof val !== 'undefined';
}
 
// 檢測變量類型是否為對象
function isObject(val) {
 return val !== null && typeof val === 'object';
}
 
// 檢測變量類型是否為空對象
function isBlankObject(val) {
 return val !== null && typeof val === 'object' && !Object.getPrototypeOf(val);
}
 
// 檢測變量類型是否為字符串
function isString(val) {
  return typeof val === 'string';
}
 
// 檢測變量類型是否為數字
function isNumber(val) {
  return typeof val === 'number';
}
 
// 檢測變量類型是否為日期
function isDate(val) {
  return toString.call(val) === '[object Date]';
}
 
// 檢測變量類型是否為函數
function isFunction(val) {
  return typeof val === 'function';
}
 
// 檢測變量類型是否為正則表達式
function isRegExp(val) {
  return toString.call(val) === '[object RegExp]';
}
 
// 檢測變量是否window窗體對象
function isWindow(obj) {
  return obj && obj.window === obj;
}
 
// 檢測變量類型是否為布爾
function isBoolean(val) {
  return typeof val === 'boolean';
}
 
// 檢測變量類型是否為文件對象
function isFile(obj) {
  return toString.call(obj) === '[object File]';
}
 
// 檢測變量類型是否為表單對象
function isFormData(obj) {
  return toString.call(obj) === '[object FormData]';
}
 
// 檢測變量類型是否為二進制對象
function isBlob(obj) {
  return toString.call(obj) === '[object Blob]';
}
 
// 轉全角字符
function toDBC(str) {
  var result = "";
  var len = str.length;
  for (var i = 0; i < len; i++) {
    var code = str.charCodeAt(i);
    //全角與半角相差(除空格外):65248(十進制)
    code = (code >= 0x0021 && code <= 0x007E) ? (code + 65248) : code;
    //處理空格
    code = (code == 0x0020) ? 0x03000 : code;
    result += String.fromCharCode(code);
  }
  return result;
}
 
// 轉半角字符
function toSBC(str) {
  var result = "";
  var len = str.length;
  for (var i = 0; i < len; i++) {
    var code = str.charCodeAt(i);
    //全角與半角相差(除空格外):65248(十進制)
    code = (code >= 0xFF01 && code <= 0xFF5E) ? (code - 65248) : code;
    //處理空格
    code = (code == 0x03000) ? 0x0020 : code;
    result += String.fromCharCode(code);
  }
  return result;
}
 
// 全角半角轉換
// angle: 0全到半,1半到全,其他不轉化
function chgAngle(str, angle) {
  if (typeof str != "string" || str.length <= 0 || !(angle === 0 || angle == 1)) {
    return str;
  }
   
  var i, len, ret = [], code;
  if (angle) {
    /*半->全*/
    for (i = 0, len = str.length; i < len; i++) {
      code = str.charCodeAt(i);
      if (code == 32) {
        code = 12288;
      } else if (code < 127) {
        code += 65248;
      }
      ret.push(String.fromCharCode(code));
    }
  } else {
    /*全->半*/
    for (i = 0, len = str.length; i < len; i++) {
      code = str.charCodeAt(i);
      if (code == 12288) {
        code = 32;
      } else if (code > 65280 && code < 65375) {
        code -= 65248;
      }
      ret.push(String.fromCharCode(code));
    }
  }
  return ret.join("");
}
 
// 數據的本地化存儲
function makeWebStorage() {
  //IE用userdata實現,w3c浏覽器本身支持
  if (("localStorage" in window)) {
    var store = {
      set  : function(key, value) {localStorage.setItem(key, value)},
      get  : function(key)    {return localStorage.getItem(key)},
      remove : function(key)    {return localStorage.removeItem(key)}
    }
  } else {
    var store = {
      userData : null,
      name   : location.hostname,
      init   : function () {
        if (!store.userData) {
          try {
            store.userData = document.createElement('INPUT');
            store.userData.type = "hidden";
            store.userData.style.display = "none";
            store.userData.addBehavior("#default#userData");
            document.body.appendChild(store.userData);
            var expires = new Date();
            expires.setDate(expires.getDate() + 365);
            store.userData.expires = expires.toUTCString();
          } catch (e) {
            return false;
          }
        }
        return true;
      },
      setItem : function(key, value) {
        if (store.init()) {
          store.userData.load(store.name);
          store.userData.setAttribute(key, value);
          store.userData.save(store.name);
        }
      },
      getItem : function(key) {
        if (store.init()) {
          store.userData.load(store.name);
          return store.userData.getAttribute(key);
        }
      },
      remove : function(key) {
        if (store.init()) {
          store.userData.load(store.name);
          store.userData.removeAttribute(key);
          store.userData.save(store.name);
        }
      }
    };
  }
  window.webStorage = store;
}
 
function makeSessionStorage() {
  if (("sessionStorage" in window)) {
    var store = {
      set  : function(key, value) {window.sessionStorage.setItem(key, value)},
      get  : function(key)    {return window.sessionStorage.getItem(key)},
      remove : function(key)    {return window.sessionStorage.removeItem(key)}
    }
  } else {
    var store = {
      set  : function(key, value) {},
      get  : function(key)    {},
      remove : function(key)    {}
    }
  }
  window.sessStorage = store;
}

以上就是小編為大家帶來的常用Javascript函數與原型功能收藏(必看篇)全部內容了,希望大家多多支持~

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved