javascript功能代码段收集

精品网站一个(js库模块):http://microjs.com

代码有自己写.整理,网上收集...

1.中英文字符长度统计

/*字符长度检测
*message,参数为要获取文本值的元素对象
*/
    function gbcount(message) {
        var lenE = message.value.length; //英文字符长度
        var lenC = 0; //中文字符长度
        var CJK = message.value.match(/[^\x00-\xff]/g); //检测有多少个中文字符
        var enter = message.value.match(/\r\n/g); //检测换行.新行
        if (CJK != null) {
            lenC += CJK.length;
        }
        if (enter != null) {
            lenC -= enter.length;
        }
        //used.value = lenE + lenC; //得出计算长度
        return lenE + lenC;
    }
显示代码

 

 2.Date时间对象扩展

/*
函数:格式化日期
参数:formatStr-格式化字符串
    d:将日显示为不带前导零的数字,如1
    dd:将日显示为带前导零的数字,如01
    ddd:将日显示为缩写形式,如Sun
    dddd:将日显示为全名,如Sunday
    M:将月份显示为不带前导零的数字,如一月显示为1
    MM:将月份显示为带前导零的数字,如01
    MMM:将月份显示为缩写形式,如Jan
    MMMM:将月份显示为完整月份名,如January
    yy:以两位数字格式显示年份
    yyyy:以四位数字格式显示年份
    h:使用12小时制将小时显示为不带前导零的数字,注意||的用法
    hh:使用12小时制将小时显示为带前导零的数字
    H:使用24小时制将小时显示为不带前导零的数字
    HH:使用24小时制将小时显示为带前导零的数字
    m:将分钟显示为不带前导零的数字
    mm:将分钟显示为带前导零的数字
    s:将秒显示为不带前导零的数字
    ss:将秒显示为带前导零的数字
    l:将毫秒显示为不带前导零的数字
    ll:将毫秒显示为带前导零的数字
    tt:显示am/pm
    TT:显示AM/PM
    返回:格式化后的日期
*/
Date.prototype.format = function (formatStr) 
{
    var date = this;
    /*
    函数:填充0字符
    参数:value-需要填充的字符串, length-总长度
    返回:填充后的字符串
    */
    var zeroize = function (value, length) 
    {
        if (!length) 
        {
            length = 2;
        }
        value = new String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++) 
        {
            zeros += '0';
        }
        return zeros + value;
    };
    return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function($0) 
    {
        switch ($0) 
        {
            case 'd': return date.getDate();
            case 'dd': return zeroize(date.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
            case 'M': return date.getMonth() + 1;
            case 'MM': return zeroize(date.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
            case 'yy': return new String(date.getFullYear()).substr(2);
            case 'yyyy': return date.getFullYear();
            case 'h': return date.getHours() % 12 || 12;
            case 'hh': return zeroize(date.getHours() % 12 || 12);
            case 'H': return date.getHours();
            case 'HH': return zeroize(date.getHours());
            case 'm': return date.getMinutes();
            case 'mm': return zeroize(date.getMinutes());
            case 's': return date.getSeconds();
            case 'ss': return zeroize(date.getSeconds());
            case 'l': return date.getMilliseconds();
            case 'll': return zeroize(date.getMilliseconds());
            case 'tt': return date.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return date.getHours() < 12 ? 'AM' : 'PM';
        }
    });
}
View Code

 2.1 取日期前后时间日期

第一版(根据今日时间,取前后日期的)

function showdate(n) {
        if (!n) {
            n = 0;
        }
        var uom = new Date(new Date() - 0 + n * 86400000);
        uom = uom.getFullYear() + "-" + (uom.getMonth() + 1) + "-" + uom.getDate();
        return uom;

    }
    log("今天是:" + showdate(0));
    log("昨天是:" + showdate(-1));
    log("明天是:" + showdate(1));
    log("10天前是:" + showdate(-10));
    log("10天后是:" + showdate(10));
View Code

修改版:(传入指定日期,取前后日期)。。。参数类型没有进行严格判断,可以自行添加验证

var log = function(a){console.log(a);};
function showdate(date,n) {
        var _temp_date = date ? new Date(date) : new Date();
        if (!n) {
            n = 0;
        }
        var uom = new Date(_temp_date - 0 + n * 86400000);
        uom = uom.getFullYear() + "-" + (uom.getMonth() + 1) + "-" + uom.getDate();
        return uom;

    }
    //调用
    log(showdate('2013-12-31',-30));

=====================对日期为单数的扑零
function showdate(s_date,n) {
        var _temp_date = s_date ? new Date(s_date) : new Date();
        if (!n) {
            n = 0;
        }
        var uom = new Date( _temp_date - 0 + n * 86400000);
        var yyyy = uom.getFullYear() + "-";
        var MM = (uom.getMonth() + 1);
        var dd = uom.getDate();
        if(MM < 10){
            MM = '0' + MM;
        }
        if(dd < 10){
            dd = '0' + dd
        }
        uom =  yyyy +  MM + "-" + dd;
        return uom;
    }
View Code

第二版

Date.prototype.format = function(fmt)
{ //author: meizz
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //
    "s+" : this.getSeconds(),                 //
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}

//写一个getDate方法
function getDate(day){
    var zdate=new Date();
    var sdate=zdate.getTime()-(1*24*60*60*1000);
    var edate=new Date(sdate-(day*24*60*60*1000)).format("yyyy-MM-dd");;
    return edate;
}

//具体用法:
getDate(6)//前七天
getDate(0)//昨天
getDate(-1)//今天
getDate(-7)
View Code

 

第三版

<script language="javascript" type="text/javascript">

    function changedate(val) {
        var currdate = "";
        var date = new Date();
                currdate = "2011-02-05";
        if (val=='0') {
            // currdate = date.getYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
        }else {
            if (chkdate(currdate)) {
                var dates = currdate.split("-");
                dates[1] = dates[1].replace(/^0/g, '');
                dates[2] = dates[2].replace(/^0/g, '');
                var currdate = DayAddDiff(parseInt(dates[0]), parseInt(dates[1]), parseInt(dates[2]), val);
            }
            else {
                var currdate = DayAddDiff(parseInt(date.getYear()), parseInt(date.getMonth() + 1), parseInt(date.getDate()), val);
            }
            
        }
       document.getElementById ("txt_Time").value = currdate;
    }


function DayAddDiff(year, month, day, diff)
{
 var numDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
 var isLeap = false;
 var newyear = year;
 var newmonth = month - 1;
 var n = numDays[newmonth];
 var newday = day;
 var newdiff = diff;
 var ln;
 if (newmonth == 0)
  ln = 31;
 else if(newmonth == 11)
  ln = 31;
 else
  ln = numDays[newmonth + 1];
 if (diff != 0){
  //判断是否润年
  if (year % 4 == 0) {
   if (year % 100 != 0)
    isLeap = true;
   else {
    if (year % 400 == 0)
     isLeap = true;
   }
  }
  if (newmonth == 1 && isLeap)
   ++n;
   
  if (newmonth == 0 && isLeap) 
   ++ln;
  //加值
  var newday = day + newdiff;
  if (newday > 0) {
   if (newday > n) {
    newday = newday - n;
    if (newmonth == 11)
     {
     newmonth = 0;
     newyear += 1;
     newdiff = newday - 1;
     return DayAddDiff(newyear, newmonth + 1, 1, newdiff);
    }
    else {
     newmonth += 1
     newdiff = newday - 1;
     return DayAddDiff(newyear, newmonth + 1, 1, newdiff);
    }
   }
  }
  else if (newday == 0) {
   if (newmonth == 0)
    {
    newmonth = 11
    newyear += -1;
    newday = 31;
   }
   else {
    newmonth += -1
    newday = numDays[newmonth];
   }
  }
  else {
   if (newmonth == 0)
    {
    newmonth = 11
    newyear += -1;
    newdiff = newday;
    newday = 31;
    return DayAddDiff(newyear, newmonth + 1, newday, newdiff);
   }
   else {
    newmonth += -1;
    newdiff = newday;
    newday = ln;
    return DayAddDiff(newyear, newmonth + 1, newday, newdiff);
   }
  }
 }
 //输出字符串
 var daystring = "";
 daystring += year;
 newmonth += 1;
 if (newmonth < 10)
    daystring += "-0" + newmonth;
 else
  daystring += "-" + newmonth;
 if (newday < 10)
     daystring += "-0" + newday;
 else
  daystring += "-" + newday;
 return daystring;
}

function chkdate(datestr) {
    var lthdatestr
    if (datestr != "")
        lthdatestr = datestr.length;
    else
        lthdatestr = 0;

    var tmpy = "";
    var tmpm = "";
    var tmpd = "";
    var datestr;
    var status;
    status = 0;
    if (lthdatestr == 0)
    //alert("日期不能为空!")
        return false;


    for (i = 0; i < lthdatestr; i++) {
        if (datestr.charAt(i) == '-') {
            status++;
        }
        if (status > 2) {
            // alert("日期格式错误!");
            return false;
        }
        if ((status == 0) && (datestr.charAt(i) != '-')) {
            tmpy = tmpy + datestr.charAt(i)
        }
        if ((status == 1) && (datestr.charAt(i) != '-')) {
            tmpm = tmpm + datestr.charAt(i)
        }
        if ((status == 2) && (datestr.charAt(i) != '-')) {
            tmpd = tmpd + datestr.charAt(i)
        }

    }
    year = new String(tmpy);
    month = new String(tmpm);
    day = new String(tmpd)
    tempdate = new String(year + month + day);
    //alert(tempdate);
    if ((tmpy.length != 4) || (tmpm.length > 2) || (tmpd.length > 2)) {
        //alert("日期格式错误!");
        return false;
    }
    if (!((1 <= month) && (12 >= month) && (31 >= day) && (1 <= day))) {
        //alert ("日期格式错误!");
        return false;
    }
    if (!((year % 4) == 0) && (month == 2) && (day == 29)) {
        //alert ("日期格式错误!");
        return false;
    }
    if ((month <= 7) && ((month % 2) == 0) && (day >= 31)) {
        //alert ("日期格式错误!");
        return false;

    }
    if ((month >= 8) && ((month % 2) == 1) && (day >= 31)) {
        //alert ("日期格式错误!");
        return false;
    }
    if ((month == 2) && (day == 30)) {
        //alert("日期格式错误!");
        return false;
    }
    //alert("对啦");
    return true;
}
 </script>

选择时间:
<input type="text" ID="txt_Time">
<a href="javascript:" onclick="javascript:changedate(-10)">前十天</a>
&nbsp;
<a href="javascript:" onclick="javascript:changedate(-1)">前一天</a>
&nbsp;
<a href="javascript:" onclick="javascript:changedate(0)">今天</a>
&nbsp;
<a href="javascript:" onclick="javascript:changedate(1)">后一天</a>
&nbsp;
<a href="javascript:" onclick="javascript:changedate(10)">后十天</a>
View Code

 2.2 取2个时间差

<script type="text/javascript">
        /* 
        * 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时:分钟:秒 
        * 其中,年月日为全格式,例如 : 2010-10-12 01:00:00 
        * 返回精度为:秒,分,小时,天
        */

        function GetDateDiff(startTime, endTime, diffType) {
            //将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式 
            startTime = startTime.replace(/\-/g, "/");
            endTime = endTime.replace(/\-/g, "/");

            //将计算间隔类性字符转换为小写
            diffType = diffType.toLowerCase();
            var sTime = new Date(startTime);      //开始时间
            var eTime = new Date(endTime);  //结束时间
            //作为除数的数字
            var divNum = 1;
            switch (diffType) {
                case "second":
                    divNum = 1000;
                    break;
                case "minute":
                    divNum = 1000 * 60;
                    break;
                case "hour":
                    divNum = 1000 * 3600;
                    break;
                case "day":
                    divNum = 1000 * 3600 * 24;
                    break;
                default:
                    break;
            }
            return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
        }
        
        var result = GetDateDiff("2010-02-26 16:00:00", "2011-07-02 21:48:40", "day");
        document.write("简明现代魔法 www.nowamagic.net 建站已有" + result + "天了。");
        //alert(result);
</script>
View Code

 

3.Class操作

// add indexOf to Array prototype for IE<8
// this isn't failsafe, but it works on our behalf
Array.prototype.CSSClassIndexOf = Array.prototype.indexOf || function (item) {
    var length = this.length;
    for (var i = 0; i<length; i++)
        if (this[i]===item) return i;
    return -1;
};
// actual Element prototype manipulation
var p = Element.prototype;
if(!p.hasClass)
    p.hasClass = function(c) {
        var r = true, e = this.className.split(' '); c = c.split(' ');
        for(var i=0; i<c.length; i++)
            if(e.CSSClassIndexOf(c[i])===-1)
                r = false;
        return r;
    };
if(!p.addClass)
    p.addClass = function(c) {
        c = c.split(' ');
        for(var i=0; i<c.length; i++)
            if(!this.hasClass(c[i]))
                this.className = this.className!==''?(this.className+' '+c[i]):c[i];
        return this;
    };
if(!p.removeClass)
    p.removeClass = function(c) {
        var e = this.className.split(' '); c = c.split(' ');
        for(var i=0; i<c.length; i++)
            if(this.hasClass(c[i]))
                e.splice(e.CSSClassIndexOf(c[i]), 1);
        this.className = e.join(' ');
        return this;
    };
if(!p.toggleClass)
    p.toggleClass = function(c) {
        c = c.split(' ');
        for(var i=0; i<c.length; i++)
            if (this.hasClass(c[i]))
                this.removeClass(c[i]);
            else
                this.addClass(c[i]);
        return this;
    };
View Code

文件地址:https://github.com/EarMaster/CSSClass

是否存在/添加/删除class

var hasClass = function(ele,cls) {
    return -1 < (" "+ele.className+" ").indexOf(" "+cls+" ");
};
var addClass = function(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
};
var removeClass = function(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
};
View Code

根据className取元素

var getElementsByClassName = function (searchClass, node,tag) {
    if(document.getElementsByClassName){
        return  document.getElementsByClassName(searchClass);
    }else{
        node = node || document;
        tag = tag || "*";
        var classes = searchClass.split(" "),
        elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
        patterns = [],
        returnElements = [],
        current,
        match;
        var i = classes.length;
        while(--i >= 0){
            patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
        }
        var j = elements.length;
        while(--j >= 0){
            current = elements[j];
            match = false;
            for(var k=0, kl=patterns.length; k<kl; k++){
                match = patterns[k].test(current.className);
                if (!match) break; 
            }
            if (match)  returnElements.push(current);
        }
        return returnElements;
    }
}
View Code

 文章一篇:http://www.cnblogs.com/Truke/archive/2013/03/11/2954685.html

 4.Event 事件

var addEvent = (function () {
    if (document.addEventListener) {
        return function (el, type, fn) {
            el.addEventListener(type, fn, false);
        };
    } else {
        return function (el, type, fn) {
            el.attachEvent('on' + type, function () {
                return fn.call(el, window.event);
            });
        };
    };
})();
View Code

 

 n.取ifrmae窗体对象和文档对象

var  _win = iframe对象.contentWindow || iframe对象;

var  _doc =  iframe对象.contentDocument || iframe对象.contentWindow.document;
View Code

 

 n.谷歌获取粘贴板内容

e.clipboardData.getData("text/html");
e.clipboardData.getData("text");
View Code

m.IE,FF获取站粘贴板内容

 function getClipboardData() {
        //IE
        if (window.clipboardData) {
            return window.clipboardData.getData("Text");
        }
        //Firxfox
        else if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("此操作被浏览器拒绝!\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
                return null;

                var clip = Components.classes['@@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) {
                    alert("粘贴板对象为空");
                    return null;
                }
                var trans = Components.classes['@@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) {
                    alert("数据转换对象为空");
                    return null;
                }
                trans.addDataFlavor('text/unicode');
                clip.getData(trans, clip.kGlobalClipboard);
                var str = new Object();
                var len = new Object();
                try {
                    trans.getTransferData('text/unicode', str, len);
                }
                catch (error) {
                    alert("粘贴数据转换出错");
                    return null;
                }
                if (str) {
                    if (Components.interfaces.nsISupportsWString)
                        str = str.value.QueryInterface(Components.interfaces.nsISupportsWString);
                    else if (Components.interfaces.nsISupportsString)
                        str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
                    else str = null;
                }
                if (str) {
                    return (str.data.substring(0, len.value / 2));
                }
            }
            return null;
        }
    }
View Code

 

用JavaScript获取选中的文字

function getSelectText() {
    return document.selection && document.selection.createRange().text || window.getSelection && window.getSelection() || document.getSelection && document.getSelection() || '';
}
View Code

http://www.keakon.net/2009/06/20/%E7%94%A8JavaScript%E8%8E%B7%E5%8F%96%E9%80%89%E4%B8%AD%E7%9A%84%E6%96%87%E5%AD%97

 

 通过新浪接口获取客户端IP地址

<script type="text/javascript" charset="gb2312" src="http://counter.sina.com.cn/ip/"></script>
<script type="text/javascript"> 
alert(ILData[0]);
</script>

ps:以前腾讯也有这种接口,现在好像不行了!

取滚动条最大值

var maxLeftscroll = ele.scrollWidth - ele.clientWidth;
ele 为有滚动条对象

 处理字符串前后空格[出自<高性能javascript>第四章,117页]

//trim 1 [最快]
if (!String.prototype.trim) { 
  String.prototype.trim = function() { 
    return this.replace(/^\s+/, "").replace(/\s+$/, ""); 
  } 
} 

var str = " \t\n test string ".trim(); 
alert(str == "test string"); // alerts "true" 


// trim 2 
String.prototype.trim = function() { 
  return this.replace(/^\s+|\s+$/g, ""); 
} 

// trim 3 
String.prototype.trim = function() { 
  return this.replace(/^\s*([\s\S]*?)\s*$/, "$1"); 
} 

// trim 4 
String.prototype.trim = function() { 
  return this.replace(/^\s*([\s\S]*\S)?\s*$/, "$1"); 
} 

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

// trim 6 
String.prototype.trim = function() { 
  var start = 0, 
      end = this.length - 1, 
      ws = " \n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003 
\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f 
\u205f\u3000\ufeff"; 
  while (ws.indexOf(this.charAt(start)) > -1) { 
    start++; 
  } 
  while (end > start && ws.indexOf(this.charAt(end)) > -1) { 
Download at www.Pin5i.Com
    end--; 
  } 
  return this.slice(start, end + 1); 
} 

 // trim 7 
String.prototype.trim = function() { 
  var str = this.replace(/^\s+/, ""), 
  end = str.length - 1, 
  ws = /\s/; 
  while (ws.test(str.charAt(end))) { 
    end--; 
  } 
  return str.slice(0, end + 1); 
} 
View Code

各游览器测试

 以下为【正美】博客中文章中招到的,收集比我的多,可以看1-2,10-13的方法。

[JavaScript trim函数大赏] http://www.cnblogs.com/rubylouvre/archive/2009/09/18/1568794.html

游览器事件之阻止默认事件和冒泡事件

preventDefault和stopPropagation翻译成原生js后
 
function preventDefault(e) {
 //如果提供了事件对象,则这是一个非IE浏览器 
 if(e && e.preventDefault) {
   //阻止默认浏览器动作(W3C)
   e.preventDefault();
 } else {
   //IE中阻止函数器默认动作的方式 
   window.event.returnValue = false; 
 }
 return false;
}
 
function stopPropagation(e) {
 //如果提供了事件对象,则这是一个非IE浏览器
 if(e && e.stopPropagation) {
   //因此它支持W3C的stopPropagation()方法
   e.stopPropagation(); 
 } else {
   //否则,我们需要使用IE的方式来取消事件冒泡 
   window.event.cancelBubble = true;
 }
 return false; 
}

这应该是平时写的默认事件和冒泡的阻止方法了。

....一大堆资料没整理...out,

  for time :2014-3-21

posted @ 2013-09-22 11:25  黑色技术  阅读(405)  评论(0编辑  收藏  举报