javascript常用方法函数收集

1
2
3
4
// 小于10补0
function  format(n) {
     return  n.toString().replace(/^(\d)$/,  '0$1' );
}

千分位显示,常用于价格显示:

1
2
3
4
// 千分位
function  toThousands(num) {
     return  parseFloat(num).toFixed(2).replace(/(\d{1,3})(?=(\d{3})+(?:\.))/g,  "$1," );
}


字符串长度截取

js 代码:
  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. }

替换全部

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

清除空格

js 代码:
  1. String.prototype.trim = function() {
  2. var reExtraSpace = /^\s*(.*?)\s+$/;
  3. return this.replace(reExtraSpace, "$1")
  4. }

清除左空格/右空格

js 代码:
  1. function ltrim(s){ return s.replace( /^(\s*| *)/, ""); }
  2. function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }

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

js 代码:
  1. String.prototype.startWith = function (s) {
  2. return this.indexOf(s) == 0
  3. }

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

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

转义html标签

js 代码:
  1. function HtmlEncode(text) {
  2. return text.replace(/&/g, '&').replace(/\"/g, '"').replace(/g, '<').replace(/>/g, '>')
  3. }

时间日期格式转换

js 代码:
  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(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
  6. str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
  7. str = str.replace(/M/g, (this.getMonth() + 1));
  8. str = str.replace(/w|W/g, Week[this.getDay()]);
  9. str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
  10. str = str.replace(/d|D/g, this.getDate());
  11. str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
  12. str = str.replace(/h|H/g, this.getHours());
  13. str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
  14. str = str.replace(/m/g, this.getMinutes());
  15. str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
  16. str = str.replace(/s|S/g, this.getSeconds());
  17. return str
  18. }

判断是否为数字类型

js 代码:
  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. }

设置cookie值

js 代码:
  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 = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;"
  9. }

获取cookie值

js 代码:
  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. }

加入收藏夹

js 代码:
  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. }

设为首页

js 代码:
  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("UniversalXPConnect")
  9. } catch(e) {
  10. alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true")
  11. }
  12. }
  13. var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
  14. prefs.setCharPref('browser.startup.homepage', 'http://w3cboy.com')
  15. }
  16. }

加载样式文件

js 代码:
  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. }

返回脚本内容

js 代码:
  1. function evalscript(s) {
  2. if(s.indexOf(') == -1) return s;
  3. var p = /]*?>([^\x00]*?)<\/script>/ig;
  4. var arr = [];
  5. while(arr = p.exec(s)) {
  6. var p1 = /]*?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 = /([^\x00]+?)<\/script>/i;
  13. arr1 = p1.exec(arr[0]);
  14. appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
  15. }
  16. }
  17. return s;
  18. }

清除脚本内容

js 代码:
  1. function stripscript(s) {
  2. return s.replace(/.*?<\/script>/ig, '');
  3. }

动态加载脚本文件

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

返回按ID检索的元素对象

js 代码:
  1. function $(id) {
  2. return !id ? null : document.getElementById(id);
  3. }

跨浏览器绑定事件

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

跨浏览器删除事件

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

为元素添加on方法

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

为元素添加trigger方法

js 代码:
  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.  
  11. NodeList.prototype.trigger = function (event) {
  12. []['forEach'].call(this, function (el) {
  13. el['trigger'](event);
  14. });
  15. return this;
  16. };

检验URL链接是否有效

js 代码:
  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. }

格式化CSS样式代码

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

压缩CSS样式代码

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

获取当前路径

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

判断是否移动设备

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

判断是否移动设备访问

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

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

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

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

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

判断是否Touch屏幕

js 代码:
  1. function isTouchScreen(){
  2. return (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
  3. }

判断是否打开视窗

js 代码:
  1. function isViewportOpen() {
  2. return !!document.getElementById('wixMobileViewport');
  3. }

获取移动设备初始化大小

js 代码:
  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. }

获取移动设备最大化大小

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

获取移动设备屏幕宽度

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

完美判断是否为网址

js 代码:
  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. }

getElementsByClassName

js 代码:
  1. function getElementsByClassName(name) {
  2. var tags = document.getElementsByTagName('*') || document.all;
  3. var els = [];
  4. for (var i = 0; i < tags.length; i++) {
  5. if (tags.className) {
  6. var cs = tags.className.split(' ');
  7. for (var j = 0; j < cs.length; j++) {
  8. if (name == cs[j]) {
  9. els.push(tags);
  10. break
  11. }
  12. }
  13. }
  14. }
  15. return els
  16. }

获取页面高度

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

获取页面scrollLeft

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

获取页面可视宽度

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

获取页面宽度

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

获取页面scrollTop

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

获取页面可视高度

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

去掉url前缀

js 代码:
  1. function removeUrlPrefix(a){
  2. a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/");
  3. while(trim(a).toLowerCase().indexOf("http://")==0){
  4. a=trim(a.replace(/http:\/\//i,""));
  5. }
  6. return a;
  7. }

随机数时间戳

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

全角半角转换

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

确认是否键盘有效输入值

js 代码:
  1. function checkKey(iKey){
  2. if(iKey == 32 || iKey == 229){return true;}/*空格和异常*/
  3. if(iKey>47 && iKey < 58){return true;}/*数字*/
  4. if(iKey>64 && iKey < 91){return true;}/*字母*/
  5. if(iKey>95 && iKey < 108){return true;}/*数字键盘1*/
  6. if(iKey>108 && iKey < 112){return true;}/*数字键盘2*/
  7. if(iKey>185 && iKey < 193){return true;}/*符号1*/
  8. if(iKey>218 && iKey < 223){return true;}/*符号2*/
  9. return false;
  10. }

获取网页被卷去的位置

js 代码:
  1. function getScrollXY() {
  2. return document.body.scrollTop ? {
  3. x: document.body.scrollLeft,
  4. y: document.body.scrollTop
  5. }:

你可能感兴趣的:(JavaScript)