【JavaScript基础】代码片段

内容简介:本文收集了许多常用的js代码,可供学习和参考!

读前笑一笑:

大灰狼边敲门边说:“小兔子乖乖,把门儿开开!”
小兔子听到后,连忙去开门:“来喽!”
兔妈妈对小兔子喊道:“不许开!是大灰狼!”
大灰狼在门口感叹道:“哎,骗一个女孩容易,骗一个女人难呀!”

*javascript动态加载

【JavaScript基础】代码片段
//方法一
function loadScript(url, callback){
    var script = document.createElement ("script")
    script.type = "text/javascript";
    if (script.readyState){ //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

//方法二
var xhr = new XMLHttpRequest();
xhr.open("get", "script1.js", true);
xhr.onreadystatechange = function(){
    if (xhr.readyState == 4){
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
            var script = document.createElement ("script");
            script.type = "text/javascript";
            script.text = xhr.responseText;
            document.body.appendChild(script);
        }
    }
};
xhr.send(null);
View Code

*阶乘缓存

【JavaScript基础】代码片段
function memfactorial(n){
    if(!memfactorial.cache){
        memfactorial.cache = {
            "0" : 1,
            "1" : 1
        };
    }
    if(!memfactorial.cache.hasOwnProperty(n)){
        memfactorial.cache[n] = n * memfactorial(n - 1);
    }
    return memfactorial.cache[n];
}
View Code

*获取字符串长度

【JavaScript基础】代码片段
//方法1
String.prototype.lengthB = function(){
    var b = 0, l = this.length;
    if(l){
        for(var i = 0; i < l; i++){
            if(this.charCodeAt(i) > 255){
                b += 2;
            }else{
                b ++;
            }
        }
        return b;
    }else{
        return 0;
    }
};

//方法2
String.prototype.lengthB2 = function(){
    var b = 0, l = this.length;
    if(l){
        for(var i = 0; i < l; i++){
            var c = this.charAt(i);
            if(escape(c).length > 4){
                b += 2;
            }else if(c != ‘\r‘){
                b ++;
            }
        }
        return b;
    }else{
        return 0;
    }
};

//方法3
String.prototype.lengthB3 = function(){
    var b = 0, l = this.length;
    if(l){
        for(var i = 0; i < l; i++){
            var c = this.charAt(i);
            if(/^[\u0000-\u00ff]$]/.test(c)){
                b ++;
            }else if(c != ‘\r‘){
                b += 2;
            }
        }
        return b;
    }else{
        return 0;
    }
};

//方法4
String.prototype.lengthB4 = function(){
   var s = this.replace(/[^\x00-\xff]/g, "**");
   return s.length;
};
View Code

*DOM加载完执行

【JavaScript基础】代码片段
function DOMLoad(fn){
    if(document.addEventListener){
        document.addEventListener("DOMContentLoaded", fn, false);
    }else{
        if(window.ActiveXObject){
            document.write("<script id=‘ie_onload‘ defer src=‘javascript:void(0)‘><\/script>");
            document.getElementById("ie_onload").onreadystatechange = function(){
                if(this.readyState == "complete"){
                    this.onreadystatechange = null;
                    fn();
                }
            }
        }
        if(/WebKit/i.test(navigator.userAgent)){
            var _timer = setInterval(function(){
                if(/loaded|complete/.test(document.readyState)){
                    clearInterval(_timer);
                    fn();
                }
            }, 10);
        }
    }
}
View Code

*获取CSS属性

【JavaScript基础】代码片段
function getStyle(e, n){
    if(e.style[n]){
        return e.style[n];
    }else if(e.currentStyle){
        return e.currentStyle[n];
    }else if(document.defaultView && document.defaultView.getComputedStyle){
        n = n.replace(/([A-Z])/g, "-$1");
        n = n.toLowerCase();
        var s = document.defaultView.getComputedStyle(e, null);
        if(s){
            return s.getPropertyValue(n);
        }
    }else{
        return null;
    }
}
View Code

*Cookie操作

【JavaScript基础】代码片段
function Cookie(name, value, options){
    if(typeof value != ‘undefined‘){
        options = options || {};
        if(value === null){
            options.expires = -1; //过期
        }
        var expires = ‘‘;
        //存在时间选项
        if(options.expires && (typeof options.expires == ‘number‘ || options.expires.toUTCString)){
            var date;
            if(typeof options.expires == ‘number‘){
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            }else{
                date = options.expires;
            }
            expires = ‘; expires=‘+date.toUTCString();
        }
        var path = options.path ? ‘; path=‘+options.path : ‘‘;
        var domain = options.domain ? ‘; domain=‘+options.domain : ‘‘;
        var secure = options.secure ? ‘; secure‘ : ‘‘;
        //写入cookie
        document.cookie = [name, ‘=‘, encodeURIComponent(value), expires, path, domain, secure].join(‘‘);
    }else{//读取cookie
        var cookValue = null;
        if(document.cookie && document.cookie != ‘‘){
            var cookie = document.cookie.split(‘;‘);
            for(var i = 0, len = cookie.length; i < len; i++){
                var cookie = (cookie[i] || ‘‘).replace(/^\s+|\s+$/g, ‘‘);
                if(cookie.substring(0, name.length + 1) == (name + ‘=‘)){
                    cookValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookValue;
    }
}
//设置
Cookie("user", "Jununx");
//获取
Cookie("user");
//删除
Cookie("user", null);
View Code

*数组检测

【JavaScript基础】代码片段
var isArray = Function.isArray || function(o){
    return typeof o === "object" && Object.prototype.toString().call(o) === "[object Array]";
};
View Code

*获取窗口位置 

【JavaScript基础】代码片段
function sereen(){
    return {
        left : window.screenLeft || window.scrollX,
        top : window.screenTop || window.scrollY
    };
}
View Code

*获取可视窗口大小

【JavaScript基础】代码片段
function client(){
    //IE6不加dtd会进入怪癖模式,client需要通过document.body获取
    return {
        width : document.documentElement.clientWidth || document.body.clientWidth,
        height : document.documentElement.clientHeight || document.body.clientHeight
    };
}
View Code

*base64编码解码 

【JavaScript基础】代码片段
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
                    this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                    this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};

//encode
Base64.encode("Test"); //VGVzdA==

//decode
Base64.decode("VGVzdA=="); // Test
View Code

*今天星期几

【JavaScript基础】代码片段
"今天是星期" + "天一二三四五六".charAt(new Date().getDay())
View Code

*页面是否在iframe里

【JavaScript基础】代码片段
if(self==top){
    //not in iframe
}else{
    //in iframe
}
View Code

*返回最小值~最大值之间随机数

【JavaScript基础】代码片段
function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
View Code

*数组合并去重

【JavaScript基础】代码片段
Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j, 1);
        }
    }
    return a;
};

var test = ["a","b"].concat(["b", "c"]).unique();
console.log(test);
View Code

*数组快排

【JavaScript基础】代码片段
function quickSort(arr) {
    if (arr.length < 2) {
        return arr;
    }
    var pivotIndex = Math.floor(arr.length / 2);
    var pivot = arr.splice(pivotIndex, 1)[0];
    var left = [];
    var right = [];
    for (var i = 0, j = arr.length; i < j; i++) {
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));
}
console.log(quickSort([1,9,2,8,3,7,4,6,5]));
View Code

*将arguments转换成数组

【JavaScript基础】代码片段
var arr = Array.prototype.slice.call(arguments, 0);
View Code

*数字金额转换成大写

【JavaScript基础】代码片段
function digit_uppercase(n) {
    var fraction = [‘角‘, ‘分‘];
    var digit = [
        ‘零‘, ‘壹‘, ‘贰‘, ‘叁‘, ‘肆‘,
        ‘伍‘, ‘陆‘, ‘柒‘, ‘捌‘, ‘玖‘
    ];
    var unit = [
        [‘元‘, ‘万‘, ‘亿‘],
        [‘‘, ‘拾‘, ‘佰‘, ‘仟‘]
    ];
    var head = n < 0? ‘欠‘: ‘‘;
    n = Math.abs(n);

    var s = ‘‘;

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ‘‘);
    }
    s = s || ‘整‘;
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = ‘‘;
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, ‘‘)
                .replace(/^$/, ‘零‘)
                + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, ‘元‘)
            .replace(/(零.)+/g, ‘零‘)
            .replace(/^整$/, ‘零元整‘);
}
View Code

*数组去重

【JavaScript基础】代码片段
function deluniqnum(arr){
    var obj = {};
    var num = [];
    for(var i in arr) {
        if(!obj[typeof (arr[i])+arr[i]]){
            num.push(arr[i]);
            obj[typeof(arr[i])+arr[i]] = ‘1‘;
        }
    }
    return num;
}
View Code

*数组随机排序

【JavaScript基础】代码片段
var arr = [1, 2, 3, 4, 5];
arr.sort(function(){
    return Math.random()>.5 ? -1 : 1;
});
View Code

*日期格式化

【JavaScript基础】代码片段
Date.prototype.toString=function(format,loc){
    var time={};
    time.Year=this.getFullYear();
    time.TYear=(""+time.Year).substr(2);
    time.Month=this.getMonth()+1;
    time.TMonth=time.Month<10?"0"+time.Month:time.Month;
    time.Day=this.getDate();
    time.TDay=time.Day<10?"0"+time.Day:time.Day;
    time.Hour=this.getHours();
    time.THour=time.Hour<10?"0"+time.Hour:time.Hour;
    time.hour=time.Hour<13?time.Hour:time.Hour-12;
    time.Thour=time.hour<10?"0"+time.hour:time.hour;
    time.Minute=this.getMinutes();
    time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;
    time.Second=this.getSeconds();
    time.TSecond=time.Second<10?"0"+time.Second:time.Second;
    time.Millisecond=this.getMilliseconds();
    time.Week=this.getDay();

    var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
    var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"];
    var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];

    var oNumber=time.Millisecond/1000;

    if(format!=undefined && format.replace(/\s/g,"").length>0){
        if(loc!=undefined && loc =="en"){
            MMMArr=MMMArrEn.slice(0);
            WeekArr=WeekArrEn.slice(0);
        }
        format=format
                .replace(/yyyy/ig,time.Year)
                .replace(/yyy/ig,time.Year)
                .replace(/yy/ig,time.TYear)
                .replace(/y/ig,time.TYear)
                .replace(/MMM/g,MMMArr[time.Month-1])
                .replace(/MM/g,time.TMonth)
                .replace(/M/g,time.Month)
                .replace(/dd/ig,time.TDay)
                .replace(/d/ig,time.Day)
                .replace(/HH/g,time.THour)
                .replace(/H/g,time.Hour)
                .replace(/hh/g,time.Thour)
                .replace(/h/g,time.hour)
                .replace(/mm/g,time.TMinute)
                .replace(/m/g,time.Minute)
                .replace(/ss/ig,time.TSecond)
                .replace(/s/ig,time.Second)
                .replace(/fff/ig,time.Millisecond)
                .replace(/ff/ig,oNumber.toFixed(2)*100)
                .replace(/f/ig,oNumber.toFixed(1)*10)
                .replace(/EEE/g,WeekArr[time.Week]);
    }
    else{
        format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;
    }
    return format;
}

var d=new Date();
console.log(d.toString());    //2012-7-27 9:26:52
console.log(d.toString(""));    //2012-7-27 9:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss"));    //2012-07-27 09:26:52
console.log(d.toString("yyyy年MM月dd日 HH:mm:ss"));    //2012年07月27日 09:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss fff"));    //2012-07-27 09:26:52 237
console.log(d.toString("yyyy年 MMM dd EEE"));    //2012年 七月 27 星期五
console.log(d.toString("yyyy MMM dd EEE","en"));    //2012 Jul 27 Fri
View Code

*五种继承方式

【JavaScript基础】代码片段
//构造函数的继承的五种方式
function Animal() {
    this.species = "dong wu";
}

//one 构造函数绑定
function Cat(name, color) {
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
}

//two prototype模式
function Cat (name, color) {
    this.name = name;
    this.color = color;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

//three 直接继承prototype
function Cat(name, color) {
    this.name = name;
    this.color = color;
}
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;

//four 利用空对象做中介
function Cat(name, color) {
    this.name = name;
    this.color = color;
}

function F(){}
F.prototype = Animal.prototype;

Cat.prototype = new F();
Cat.prototype.constructor = Cat;


//five 拷贝继承
function Cat(name, color) {
    this.name = name;
    this.color = color;
}

function extend(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
        c[i] = p[i];
    }
    c.uber = p;
}
extend(Cat, Animal);
View Code

*根据生日算年龄

【JavaScript基础】代码片段
function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log(getAge("1990,1,12"));
View Code

*简单事件绑定

【JavaScript基础】代码片段
//添加事件
function addEvent(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent) {
        obj.attachEvent(‘on‘ + type, fn);
    }
}

//移除事件
function removeEvent(obj, type, fn) {
    if (obj.removeEventListener) {
        obj.removeEventListener(type, fn, false);
    } else if (obj.detachEvent) {
        obj.detachEvent(‘on‘ + type, fn);
    }
}
View Code

*获取class

【JavaScript基础】代码片段
function getElementsByClassName(node,classname) {
    if (node.getElementsByClassName) {
        return node.getElementsByClassName(classname);
    } else {
        return (function getElementsByClass(searchClass,node) {
            if ( node == null )
                node = document;
            var classElements = [],
                    els = node.getElementsByTagName("*"),
                    elsLen = els.length,
                    pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

            for (i = 0, j = 0; i < elsLen; i++) {
                if ( pattern.test(els[i].className) ) {
                    classElements[j] = els[i];
                    j++;
                }
            }
            return classElements;
        })(classname, node);
    }
}
View Code

*获取scrollTop

【JavaScript基础】代码片段
function getScrollTop(){
    if(typeof pageYOffset!= ‘undefined‘){
        return pageYOffset;
    }
    else{
        var B= document.body;
        var D= document.documentElement;
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}
View Code

*加载获取图片尺寸

【JavaScript基础】代码片段
var img = new Image();
img.onload = function() {
    console.log(this.width + ‘x‘ + this.height);
}
View Code

*不用new生成构造函数

【JavaScript基础】代码片段
var create = Object.create || function(o){
    var F = function(o){};
    F.prototype = o;
    return new F;
};
View Code

*浏览器判断

【JavaScript基础】代码片段
var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                                (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

if (Sys.ie) document.write(‘IE: ‘ + Sys.ie);
if (Sys.firefox) document.write(‘Firefox: ‘ + Sys.firefox);
if (Sys.chrome) document.write(‘Chrome: ‘ + Sys.chrome);
if (Sys.opera) document.write(‘Opera: ‘ + Sys.opera);
if (Sys.safari) document.write(‘Safari: ‘ + Sys.safari);
View Code

*IE版本判断

【JavaScript基础】代码片段
var _IE = (function(){
    var v = 3, div = document.createElement(‘div‘), all = div.getElementsByTagName(‘i‘);
    while (
            div.innerHTML = ‘<!--[if gt IE ‘ + (++v) + ‘]><i></i><![endif]-->‘,
                    all[0]
            );
    return v > 4 ? v : false ;
}());
View Code

*获取选择文本

【JavaScript基础】代码片段
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    }else if (document.getSelection) {
        return document.getSelection();
    }else {
        return document.selection.createRange().text;
    }
}
View Code

*加载样式表

【JavaScript基础】代码片段
function addSheet(url){
    var oLink = document.createElement(‘link‘),oHead = document.getElementsByTagName(‘head‘)[0];
    oLink.rel = ‘stylesheet‘;
    oLink.type = ‘text/css‘;
    oLink.href = url;
    oHead.appendChild(oLink);
}
View Code

*JSONP调用

【JavaScript基础】代码片段
<script src="http://www.xxx.com?name=jsonp"></script>
<script>
function jsonp(info){
    //提供一个方法http://www.xxx.com?name=jsonp执行
}
</script>
View Code

*获取服务器时间

【JavaScript基础】代码片段
var xhr = new XMLHttpRequest();
xhr.open(‘get‘, ‘null.txt‘, true); //null.txt不存在,我们不需要
xhr.onreadystatechange = function(){
    if(xhr.readyState == 3){ //状态3响应
        var header = xhr.getAllResponseHeaders(); //获得所有的头信息
        console.log(header);//会弹出一堆信息
        console.log(xhr.getResponseHeader(‘Date‘)); //弹出时间,那么可以利用获得的时间做倒计时程序了。
    }
};
xhr.send(null);
View Code

*flash插件检测 

【JavaScript基础】代码片段
//IE
function hasIEPlugin(name){
    try{
        new ActiveXObject(name);
        return true;
    }catch (e){
        return false;
    }
}
//非IE
function hasPlugin(name){
    var name = name.toLowerCase();
    for(var i = 0; i < navigator.plugins.length; i++){
        if(navigator.plugins[i].name.toLowerCase().indexOf(name) > -1){
            return true;
        }
    }

    return false;
}

function hasFlash(){
    var result = hasPlugin(‘Flash‘);

    if(!result){ //IE或者没有flash
        return hasIEPlugin(‘ShockwaveFlash.ShockwaveFlash‘); //参数是flash的某一标示符
    }
    return result;
}
View Code

*获取域名

【JavaScript基础】代码片段
window.location.href.match(/^\w+\:\/\/([^\/]*).*/)
View Code

*选择框跳转页面

【JavaScript基础】代码片段
<select onchange="window.open(this.options[this.selectedIndex].value)">
    <option value="http://www.baidu.com/">百度</option>
    <option value="http://www.163.com/">网易</option>
</select>
View Code

*IE6里a:hover图片缓存

【JavaScript基础】代码片段
document.execCommand("BackgroundImageCache",false,true);
View Code

*反转文本顺序

【JavaScript基础】代码片段
var aTxt = ‘反转文本顺序‘.split(‘‘),str = ‘‘;
for(var i=aTxt.length-1;i>=0;i--){
  str += aTxt[i]
}
View Code

*清除空格

【JavaScript基础】代码片段
String.prototype.trim = String.trim || function() {
    return this.replace(/^\s*(.*?)\s+$/, "$1")
};
View Code

*随机字符串

【JavaScript基础】代码片段
 function randInt (num1, num2){  //# 随机整数
    if(num2 == undefined){
        num2 = num1;
        num1 = 0;
    }
    return Math.floor( Math.random() * (num2-num1) +num1 );
}
function randWord( wordLen, baseWord ){ //# 随机字符串
    var words = baseWord || ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+‘
            , length = words.length
            , len = parseInt( wordLen ) || 0 //输出单词长度
            , out = [] //记录字符
            , pos = 0 // 记录位置
            ;
    while( len-- ){
        pos = randInt(0, length );
        out.push( words[ pos ] );
    }
    return out.join(‘‘);
}
View Code

*数组index

【JavaScript基础】代码片段
function index(t, arr){
    if(arr.indexOf){
        return arr.indexOf(t);
    }
    for(var i = arr.length ; i--; ){
        if(arr[i]===t){
            return i*1;
        }
    }
    return -1;
}
View Code

*获取数组中最小/大值

【JavaScript基础】代码片段
var max = Math.max.apply(null, array);
var min = Math.min.apply(null, array);
View Code

*URL操作

【JavaScript基础】代码片段
var getURL = {
    //参数:变量名,url为空则表从当前页面的url中取
    getQuery : function(name, url){
        var u          = arguments[1] || window.location.search
                , reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)")
                , r = u.substr(u.indexOf("?")+1).match(reg)
                ;
        return r != null ? r[2] : "";
    }
    , getHash : function(name, url){ //# 获取 hash值
        var u = arguments[1] || location.hash;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = u.substr(u.indexOf("#") + 1).match(reg);
        if (r != null){
            return r[2];
        }
        return "";
    }
    , parse : function(url) { //# 解析URL
        var a =  document.createElement(‘a‘);
        url = url || document.location.href;
        a.href = url ;
        return {
            source        : url
            , protocol    : a.protocol.replace(‘:‘,‘‘)
            , host        : a.hostname
            , port        : a.port
            , query        : a.search
            , file        : (a.pathname.match(/([^\/?#]+)$/i) || [,‘‘])[1]
            , hash        : a.hash.replace(‘#‘,‘‘)
            , path        : a.pathname.replace(/^([^\/])/,‘/$1‘)
            , relative    : (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,‘‘])[1]
            , segments    : a.pathname.replace(/^\//,‘‘).split(‘/‘)
        };
    }
};
View Code

*常用正则

【JavaScript基础】代码片段
var regExps = {  //# 字符串匹配
    //是否为 数字!整数,浮点数
    isNum : function( num ){ //# 是否为数组
        return ! isNaN( num ) ;
    }
    , isEmail : function( mail ){//# 是否为 邮箱
        return /^([a-z0-9]+[_\-\.]?)*[a-z0-9]+@([a-z0-9]+[_\-\.]?)*[a-z0-9]+\.[a-z]{2,5}$/i.test( mail );
    }
    , isIdCard : function( card ){ //# 是否为 身份证
        return /^(\d{14}|\d{17})(\d|[xX])$/.test( card );
    }
    , isMobile : function( mobile ){ //# 是否为 手机
        return /^0*1\d{10}$/.test( mobile ) ;
    }
    , isQQ : function( qq ){ //# 是否为 QQ
        return /^[1-9]\d{4,10}$/.test( qq );
    }
    , isTel:function( tel ){ //# 是否为 电话
        return /^\d{3,4}-\d{7,8}(-\d{1,6})?$/.text( tel ) ;
    }
    , isUrl : function( url ){ //# 是否为 URL
        return /https?:\/\/[a-z0-9\.\-]{1,255}\.[0-9a-z\-]{1,255}/i.test( url );
    }
    , isColor : function( color ){ //# 是否为 16进制颜色
        return /#([\da-f]{3}){1,2}$/i.test( color );
    }
    //@id : 身份证 ,
    // @now : 当前时间 如:new Date(‘2013/12/12‘) , ‘2013/12/12‘
    // @age : 允许的年龄
    , isAdult : function( id, allowAge, now ){ //# 是否年龄是否成年
        var age = 0 // 用户 年月日
                , nowDate = 0  //当前年月日
                ;
        allowAge = parseFloat( allowAge ) || 18;
        now = typeof now == ‘string‘ ? new Date( now ) : ( now || new Date() );


        if( ! this.isIdCard( id ) ){
            return false ;
        }
        //15位身份证
        if( 15 == id.length ){
            age = ‘19‘+ id.slice(6, 6);
        }else{
            age = id.slice(6, 14);
        }
        // 类型转换 整型
        age = ~~age;
        nowDate = ~~( julyJs.date.format(‘YYYYMMDD‘, now) );
        //比较年龄
        if( nowDate - age < allowAge * 1e4 ){
            return false ;
        }
        return true ;
    }
    //浮点数
    , isFloat : function( num ){ //# 是否为 浮点数
        return /^(([1-9]\d*)|(\d+\.\d+)|0)$/.test( num );
    }
    //正整数
    , isInt : function( num ){ //# 是否为 正整数
        return /^[1-9]\d*$/.test( num );
    }
    //是否全为汉字
    , isChinese : function( str ){ //# 是否全为 汉字
        return /^([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+$/gi.test(str);
    }

};
View Code

*加密

【JavaScript基础】代码片段
var encrypt = { //# 加密
    md5 : function( words ){  //# md5 哈希算法
        /*
         * Crypto-JS 3.1.2
         * http://code.google.com/p/crypto-js
         */
        var CryptoJS=function(s,p){var m={},l=m.lib={},n=function(){},r=l.Base={extend:function(b){n.prototype=this;var h=new n;b&&h.mixIn(b);h.hasOwnProperty("init")||(h.init=function(){h.$super.init.apply(this,arguments)});h.init.prototype=h;h.$super=this;return h},create:function(){var b=this.extend();b.init.apply(b,arguments);return b},init:function(){},mixIn:function(b){for(var h in b)b.hasOwnProperty(h)&&(this[h]=b[h]);b.hasOwnProperty("toString")&&(this.toString=b.toString)},clone:function(){return this.init.prototype.extend(this)}},q=l.WordArray=r.extend({init:function(b,h){b=this.words=b||[];this.sigBytes=h!=p?h:4*b.length},toString:function(b){return(b||t).stringify(this)},concat:function(b){var h=this.words,a=b.words,j=this.sigBytes;b=b.sigBytes;this.clamp();if(j%4)for(var g=0;g<b;g++)h[j+g>>>2]|=(a[g>>>2]>>>24-8*(g%4)&255)<<24-8*((j+g)%4);else if(65535<a.length)for(g=0;g<b;g+=4)h[j+g>>>2]=a[g>>>2];else h.push.apply(h,a);this.sigBytes+=b;return this},clamp:function(){var b=this.words,h=this.sigBytes;b[h>>>2]&=4294967295<<32-8*(h%4);b.length=s.ceil(h/4)},clone:function(){var b=r.clone.call(this);b.words=this.words.slice(0);return b},random:function(b){for(var h=[],a=0;a<b;a+=4)h.push(4294967296*s.random()|0);return new q.init(h,b)}}),v=m.enc={},t=v.Hex={stringify:function(b){var a=b.words;b=b.sigBytes;for(var g=[],j=0;j<b;j++){var k=a[j>>>2]>>>24-8*(j%4)&255;g.push((k>>>4).toString(16));g.push((k&15).toString(16))}return g.join("")},parse:function(b){for(var a=b.length,g=[],j=0;j<a;j+=2)g[j>>>3]|=parseInt(b.substr(j,2),16)<<24-4*(j%8);return new q.init(g,a/2)}},a=v.Latin1={stringify:function(b){var a=b.words;b=b.sigBytes;for(var g=[],j=0;j<b;j++)g.push(String.fromCharCode(a[j>>>2]>>>24-8*(j%4)&255));return g.join("")},parse:function(b){for(var a=b.length,g=[],j=0;j<a;j++)g[j>>>2]|=(b.charCodeAt(j)&255)<<24-8*(j%4);return new q.init(g,a)}},u=v.Utf8={stringify:function(b){try{return decodeURIComponent(escape(a.stringify(b)))}catch(g){throw Error("Malformed UTF-8 data");}},parse:function(b){return a.parse(unescape(encodeURIComponent(b)))}},
                g=l.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(b){"string"==typeof b&&(b=u.parse(b));this._data.concat(b);this._nDataBytes+=b.sigBytes},_process:function(b){var a=this._data,g=a.words,j=a.sigBytes,k=this.blockSize,m=j/(4*k),m=b?s.ceil(m):s.max((m|0)-this._minBufferSize,0);b=m*k;j=s.min(4*b,j);if(b){for(var l=0;l<b;l+=k)this._doProcessBlock(g,l);l=g.splice(0,b);a.sigBytes-=j}return new q.init(l,j)},clone:function(){var b=r.clone.call(this);b._data=this._data.clone();return b},_minBufferSize:0});l.Hasher=g.extend({cfg:r.extend(),init:function(b){this.cfg=this.cfg.extend(b);this.reset()},reset:function(){g.reset.call(this);this._doReset()},update:function(b){this._append(b);this._process();return this},finalize:function(b){b&&this._append(b);return this._doFinalize()},blockSize:16,_createHelper:function(b){return function(a,g){return(new b.init(g)).finalize(a)}},_createHmacHelper:function(b){return function(a,g){return(new k.HMAC.init(b,g)).finalize(a)}}});var k=m.algo={};return m}(Math);
        (function(s){function p(a,k,b,h,l,j,m){a=a+(k&b|~k&h)+l+m;return(a<<j|a>>>32-j)+k}function m(a,k,b,h,l,j,m){a=a+(k&h|b&~h)+l+m;return(a<<j|a>>>32-j)+k}function l(a,k,b,h,l,j,m){a=a+(k^b^h)+l+m;return(a<<j|a>>>32-j)+k}function n(a,k,b,h,l,j,m){a=a+(b^(k|~h))+l+m;return(a<<j|a>>>32-j)+k}for(var r=CryptoJS,q=r.lib,v=q.WordArray,t=q.Hasher,q=r.algo,a=[],u=0;64>u;u++)a[u]=4294967296*s.abs(s.sin(u+1))|0;q=q.MD5=t.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(g,k){for(var b=0;16>b;b++){var h=k+b,w=g[h];g[h]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var b=this._hash.words,h=g[k+0],w=g[k+1],j=g[k+2],q=g[k+3],r=g[k+4],s=g[k+5],t=g[k+6],u=g[k+7],v=g[k+8],x=g[k+9],y=g[k+10],z=g[k+11],A=g[k+12],B=g[k+13],C=g[k+14],D=g[k+15],c=b[0],d=b[1],e=b[2],f=b[3],c=p(c,d,e,f,h,7,a[0]),f=p(f,c,d,e,w,12,a[1]),e=p(e,f,c,d,j,17,a[2]),d=p(d,e,f,c,q,22,a[3]),c=p(c,d,e,f,r,7,a[4]),f=p(f,c,d,e,s,12,a[5]),e=p(e,f,c,d,t,17,a[6]),d=p(d,e,f,c,u,22,a[7]),c=p(c,d,e,f,v,7,a[8]),f=p(f,c,d,e,x,12,a[9]),e=p(e,f,c,d,y,17,a[10]),d=p(d,e,f,c,z,22,a[11]),c=p(c,d,e,f,A,7,a[12]),f=p(f,c,d,e,B,12,a[13]),e=p(e,f,c,d,C,17,a[14]),d=p(d,e,f,c,D,22,a[15]),c=m(c,d,e,f,w,5,a[16]),f=m(f,c,d,e,t,9,a[17]),e=m(e,f,c,d,z,14,a[18]),d=m(d,e,f,c,h,20,a[19]),c=m(c,d,e,f,s,5,a[20]),f=m(f,c,d,e,y,9,a[21]),e=m(e,f,c,d,D,14,a[22]),d=m(d,e,f,c,r,20,a[23]),c=m(c,d,e,f,x,5,a[24]),f=m(f,c,d,e,C,9,a[25]),e=m(e,f,c,d,q,14,a[26]),d=m(d,e,f,c,v,20,a[27]),c=m(c,d,e,f,B,5,a[28]),f=m(f,c,d,e,j,9,a[29]),e=m(e,f,c,d,u,14,a[30]),d=m(d,e,f,c,A,20,a[31]),c=l(c,d,e,f,s,4,a[32]),f=l(f,c,d,e,v,11,a[33]),e=l(e,f,c,d,z,16,a[34]),d=l(d,e,f,c,C,23,a[35]),c=l(c,d,e,f,w,4,a[36]),f=l(f,c,d,e,r,11,a[37]),e=l(e,f,c,d,u,16,a[38]),d=l(d,e,f,c,y,23,a[39]),c=l(c,d,e,f,B,4,a[40]),f=l(f,c,d,e,h,11,a[41]),e=l(e,f,c,d,q,16,a[42]),d=l(d,e,f,c,t,23,a[43]),c=l(c,d,e,f,x,4,a[44]),f=l(f,c,d,e,A,11,a[45]),e=l(e,f,c,d,D,16,a[46]),d=l(d,e,f,c,j,23,a[47]),c=n(c,d,e,f,h,6,a[48]),f=n(f,c,d,e,u,10,a[49]),e=n(e,f,c,d,
                C,15,a[50]),d=n(d,e,f,c,s,21,a[51]),c=n(c,d,e,f,A,6,a[52]),f=n(f,c,d,e,q,10,a[53]),e=n(e,f,c,d,y,15,a[54]),d=n(d,e,f,c,w,21,a[55]),c=n(c,d,e,f,v,6,a[56]),f=n(f,c,d,e,D,10,a[57]),e=n(e,f,c,d,t,15,a[58]),d=n(d,e,f,c,B,21,a[59]),c=n(c,d,e,f,r,6,a[60]),f=n(f,c,d,e,z,10,a[61]),e=n(e,f,c,d,j,15,a[62]),d=n(d,e,f,c,x,21,a[63]);b[0]=b[0]+c|0;b[1]=b[1]+d|0;b[2]=b[2]+e|0;b[3]=b[3]+f|0},_doFinalize:function(){var a=this._data,k=a.words,b=8*this._nDataBytes,h=8*a.sigBytes;k[h>>>5]|=128<<24-h%32;var l=s.floor(b/4294967296);k[(h+64>>>9<<4)+15]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360;k[(h+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;a.sigBytes=4*(k.length+1);this._process();a=this._hash;k=a.words;for(b=0;4>b;b++)h=k[b],k[b]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;return a},clone:function(){var a=t.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=t._createHelper(q);r.HmacMD5=t._createHmacHelper(q)})(Math);
        return CryptoJS.MD5( words).toString() ;
    }
    // sha1
    , sha1 : function( words ){ //# sha1  哈希算法
        var CryptoJS=function(e,m){var p={},j=p.lib={},l=function(){},f=j.Base={extend:function(a){l.prototype=this;var c=new l;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},n=j.WordArray=f.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=m?c:4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var c=this.words,q=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b<a;b++)c[d+b>>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535<q.length)for(b=0;b<a;b+=4)c[d+b>>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<32-8*(c%4);a.length=e.ceil(c/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b<a;b+=4)c.push(4294967296*e.random()|0);return new n.init(c,a)}}),b=p.enc={},h=b.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d<a;d++){var f=c[d>>>2]>>>24-8*(d%4)&255;b.push((f>>>4).toString(16));b.push((f&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],d=0;d<c;d+=2)b[d>>>3]|=parseInt(a.substr(d,2),16)<<24-4*(d%8);return new n.init(b,c/2)}},g=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d<a;d++)b.push(String.fromCharCode(c[d>>>2]>>>24-8*(d%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],d=0;d<c;d++)b[d>>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new n.init(b,c)}},r=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(g.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return g.parse(unescape(encodeURIComponent(a)))}},k=j.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new n.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=r.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,d=c.sigBytes,f=this.blockSize,h=d/(4*f),h=a?e.ceil(h):e.max((h|0)-this._minBufferSize,0);a=h*f;d=e.min(4*a,d);if(a){for(var g=0;g<a;g+=f)this._doProcessBlock(b,g);g=b.splice(0,a);c.sigBytes-=d}return new n.init(g,d)},clone:function(){var a=f.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});j.Hasher=k.extend({cfg:f.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){k.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,b){return(new a.init(b)).finalize(c)}},_createHmacHelper:function(a){return function(b,f){return(new s.HMAC.init(a,f)).finalize(b)}}});var s=p.algo={};return p}(Math);
        (function(){var e=CryptoJS,m=e.lib,p=m.WordArray,j=m.Hasher,l=[],m=e.algo.SHA1=j.extend({_doReset:function(){this._hash=new p.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(f,n){for(var b=this._hash.words,h=b[0],g=b[1],e=b[2],k=b[3],j=b[4],a=0;80>a;a++){if(16>a)l[a]=f[n+a]|0;else{var c=l[a-3]^l[a-8]^l[a-14]^l[a-16];l[a]=c<<1|c>>>31}c=(h<<5|h>>>27)+j+l[a];c=20>a?c+((g&e|~g&k)+1518500249):40>a?c+((g^e^k)+1859775393):60>a?c+((g&e|g&k|e&k)-1894007588):c+((g^e^k)-899497514);j=k;k=e;e=g<<30|g>>>2;g=h;h=c}b[0]=b[0]+h|0;b[1]=b[1]+g|0;b[2]=b[2]+e|0;b[3]=b[3]+k|0;b[4]=b[4]+j|0},_doFinalize:function(){var f=this._data,e=f.words,b=8*this._nDataBytes,h=8*f.sigBytes;e[h>>>5]|=128<<24-h%32;e[(h+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(h+64>>>9<<4)+15]=b;f.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=j.clone.call(this);e._hash=this._hash.clone();return e}});e.SHA1=j._createHelper(m);e.HmacSHA1=j._createHmacHelper(m)})();
        return CryptoJS.SHA1( words).toString();
    }
    // time33 哈希
    , time33 : function( words ){ //# time33 哈希算法
        words = words || ‘‘;
        //哈希time33算法
        for(var i = 0, len = words.length, hash = 5381; i < len; ++i){
            hash += ( hash << 5) + words.charAt(i).charCodeAt();
        };
        return hash & 0x7fffffff;
    }
}
View Code

*敏感词过滤 

【JavaScript基础】代码片段
 function badWord( text, words){
    text = String( text || ‘‘ );
    words = words || [];
    var reg = new RegExp( words.join(‘|‘) , ‘g‘)
            , _self = this ;
    return text.replace( reg, function( $0 ){
        var length = String( $0 || ‘‘ ).length ;
        return _self.repeat( ‘*‘, length);
    });
}
View Code

*加入收藏

【JavaScript基础】代码片段
function AddFavorite(url, title) {
    try {
        window.external.addFavorite(url, title)
    } catch(e) {
        try {
            window.sidebar.addPanel(title, url, "")
        } catch(e) {
            alert("加入收藏失败,请使用Ctrl+D进行添加")
        }
    }
}
View Code

*设为首页

【JavaScript基础】代码片段
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)
    }
}
View Code

*insertAfter

【JavaScript基础】代码片段
function insertAfter(newChild,refChild){
    var parElem=refChild.parentNode;
    if(parElem.lastChild==refChild){
        refChild.appendChild(newChild);
    }else{
        parElem.insertBefore(newChild,refChild.nextSibling);
    }
}
View Code

*hasClass

【JavaScript基础】代码片段
function hasClass (element, className){
    return element.className.match(new RegExp(‘(\\s|^)‘+ className +‘(\\s|$)‘));
};
View Code

*addClass

【JavaScript基础】代码片段
//添加一个class
function addClass(element, cName) {
    if (!hasClass(element, cName)) {
        element.className += ‘ ‘ + cName;
    }
}
View Code

*removeClass

【JavaScript基础】代码片段
//移除一个class
function removeClass(element, cName) {
    if (hasClass(element, cName)) {
        element.className = element.className.replace(new RegExp(‘(\\s|^)‘ + cName + ‘(\\s|$)‘), ‘ ‘);
    }
}
View Code

*Link规则操作

【JavaScript基础】代码片段
//添加第一条规则
//insertRule(sheet, ‘body‘, ‘background-color:red‘, 0);
function insertRule(sheet, selectorText, cssText, position) {
    if (sheet.insertRule) {
        sheet.insertRule(selectorText + ‘ { ‘ + cssText + ‘ }‘, position);
    } else if (sheet.addRule) {
        sheet.addRule(selectorText, cssText, position);
    }
}


//删除第一条规则
//deleteRule(sheet, 0);
function deleteRule(sheet, position) {
    if (sheet.deleteRule) {
        sheet.deleteRule(position);
    } else if (sheet.removeRule) {
        sheet.removeRule(position);
    }
}
View Code

*获取Event

【JavaScript基础】代码片段
function getEvent(event){
    return event || window.event;
}
View Code

*事件绑定

【JavaScript基础】代码片段
var addEvent_id = 1;
function addEvent(obj, type, fn){
    if(typeof obj.addEventListener != ‘undefined‘){
        obj.addEventListener(type, fn, false);
    }else if(typeof obj.attachEvent != ‘undefined‘){
        //创建存放事件的表
        if(!obj.events) obj.events = {};

        //第一次
        if(!obj.events[type]){
            //创建存放事件数组
            obj.events[type] = [];
            //储存第一次
            if(obj[‘on‘+type]) obj.events[type][0] = fn;
        }

        //第2次开始
        obj.events[type][addEvent_id++] = fn;
        //执行事件处理函数
        obj[‘on‘+type] = function(){
            for(var i in obj.events[type]){
                obj.events[type][i]();
            }
        };
    }
}
View Code

*IE是否标准模式

【JavaScript基础】代码片段
function isCompatMode(){return document.compatMode == ‘CSS1Compat‘;}
View Code

*innerText操作

【JavaScript基础】代码片段
//获取innertext
function getInnerText(element) {
    if (typeof element.textContent == ‘string‘) {
        return element.textContent;
    } else {
        return element.innerText;
    }
}
//设置innertext
function setInnerText(element, text) {
    if (typeof element.textContent == ‘string‘) {
        element.textContent = text;
    } else {
        element.innerText = text;
    }
}
View Code

*获取offsetTop

【JavaScript基础】代码片段
//获取offsetTop
function offsetTop(element) {
    var top = element.offsetTop;        //第一层的距离
    var parent = element.offsetParent;

    while (parent !== null) {
        top += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return top;
}
View Code

*获取key

【JavaScript基础】代码片段
//获取key
function getKey(evt) {
    var e = evt || window.event;
    var keys = [];

    if (e.shiftKey) keys.push(‘shift‘);
    if (e.ctrlKey) keys.push(‘ctrl‘);
    if (e.altKey) keys.push(‘alt‘);                        //单击+alt和360的快捷键冲突了
    return keys;
}
View Code

*字符按键

【JavaScript基础】代码片段
//字符按键
function getCharCode(evt) {
    var e = evt || window.event;
    if (typeof e.charCode == ‘number‘) {
        return e.charCode;
    } else {
        return e.keyCode;
    }
}
View Code

*获取目标对象target

【JavaScript基础】代码片段
function getTarget(evt) {
    if (evt.target) {        //W3C
        return evt.target;
    } else if (window.event.srcElement) {        //IE
        return window.event.srcElement;
    }
}
View Code

*阻止默认行为

【JavaScript基础】代码片段
function preDef(evt) {
    var e = evt || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}
View Code

*选定文本

【JavaScript基础】代码片段
//选定文本
function getSelectText(text, start, num) {
    if (text.setSelectionRange) {
        text.setSelectionRange(start,num);
        text.focus();
    } else if (text.createTextRange) {
        var range = text.createTextRange();
        range.collapse(true);
        range.moveStart(‘character‘,start);
        range.moveEnd(‘character‘,num - start);                //用最后的位置 - 开始的位置 = 个数
        range.select();
    }
}
View Code

*XML操作

【JavaScript基础】代码片段
//XML DOM对象
function getXMLDOM(xmlStr) {
    var xmlDom = null;

    if (typeof window.DOMParser != ‘undefined‘) {
        xmlDom = (new DOMParser).parseFromString(xmlStr, ‘text/xml‘);
        var errors = xmlDom.getElementsByTagName(‘parsererror‘);
        if (errors.length > 0) {
            throw new Error(‘错误信息:‘ + errors[0].textContent);
        }
    } else if (typeof window.ActiveXObject != ‘undefined‘) {
        var version = [
            ‘MSXML2.DOMDocument6.0‘,
            ‘MSXML2.DOMDocument3.0‘,
            ‘MSXML2.DOMDocument‘
        ];

        for (var i = 0; i < version.length; i ++) {
            try {
                var xmlDom = new ActiveXObject(version[i]);
            } catch (e) {
                //跳过
            }
        }
        xmlDom.loadXML(xmlStr);
        if (xmlDom.parseError != 0) {
            throw new Error(‘错误信息:‘ + xmlDom.parseError.reason);
        }
        return xmlDom;
    } else {
        throw new Error(‘您的系统或浏览器不支持XML DOM对象!‘);
    }

    return xmlDom;
}

//序列化XML
function serializerXML(xmlDom) {
    var xml = ‘‘;

    if (typeof window.XMLSerializer != ‘undefined‘) {
        xml = (new XMLSerializer()).serializeToString(xmlDom);
    } else if (typeof xmlDom.xml != ‘undefined‘) {
        xml = xmlDom.xml;
    }

    return xml;
}

//单一节点
function selectSingleNode(xmlDom, xpath) {
    var node = null;
    if (typeof xmlDom.evaluate != ‘undefined‘) {        //W3C
        var patten = /\[(\d+)\]/;
        var flag = xpath.match(patten);
        var num = 0;
        if (flag !== null) {
            num = parseInt(RegExp.$1) + 1;
            xpath = xpath.replace(patten, ‘[‘ + num + ‘]‘);
        }
        var result = xmlDom.evaluate(xpath, xmlDom, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        if (result !== null) {
            node = result.singleNodeValue;
        }
    } else if (typeof xmlDom.selectSingleNode != ‘undefined‘) {        //IE
        node = xmlDom.selectSingleNode(xpath);
    }

    return node;
}

//节点集合
function selectNodes(xmlDom, xpath) {
    var nodes = [];
    if (typeof xmlDom.evaluate != ‘undefined‘) {        //W3C
        var patten = /\[(\d+)\]/;
        var flag = xpath.match(patten);
        var num = 0;
        if (flag !== null) {
            num = parseInt(RegExp.$1) + 1;
            xpath = xpath.replace(patten, ‘[‘ + num + ‘]‘);
        }
        var result = xmlDom.evaluate(xpath, xmlDom, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
        if (result != null) {
            var node = null;
            while ((node = result.iterateNext()) !== null) {
                nodes.push(node);
            }
        }
    } else if (typeof xmlDom.selectNodes != ‘undefined‘) {        //IE
        nodes = xmlDom.selectNodes(xpath);
    }

    return nodes;
}
View Code

 

 by jununx@gamil.com 

【JavaScript基础】代码片段,布布扣,bubuko.com

【JavaScript基础】代码片段

上一篇:js 方法的一些简写和技巧


下一篇:递归与分治策略