JS實用技巧手記(七)

2018-06-17 19:27 更新

本系列文章旨在記錄一些實用的javascript技巧,既可以作為一個知識的積累,又可以作為閑暇時打發(fā)時間寫寫代碼的記錄。同時也方便日后翻閱~

1. 操作DOM class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 判斷某個對象是否有指定的className
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
// 給指定對象添加className
function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
// 刪除className
function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}

2. 分解url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 正則:
/^([^:]+):\/\/(?:([^:@]+):?([^@]*)@)?(?:([^/?#:]+):?(\d*))([^?#]*)(?:\?([^#]+)?)?(?:#(.+)?)?$/
// 結(jié)果格式:
Array
    [scheme] => http
    [host] => quchao.com
    [user] => user
    [pass] => pass
    [path] => /about-me
    [query] => t=100102
    [fragment] => hash
)
// demo:
'http://user:pass@xuanfenge.com:80/category/?s=css3#first'
.match(/^([^:]+):\/\/(?:([^:@]+):?([^@]*)@)?(?:([^/?#:]+):?(\d*))([^?#]*)(?:\?([^#]+)?)?(?:#(.+)?)?$/);
// 結(jié)果
["http://user:pass@xuanfenge.com:80/category/?s=css3#first", "http", "user", "pass", "xuanfenge.com", "80", "/category/", "s=css3", "first"]

3. 獲取url參數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function parseUrl(url) {
    // 找到url中的第一個?號
    var parse = url.substring(url.indexOf("?") + 1),
        params = parse.split("&"),
        len = params.length,
        item = [],
        param = {};
    for (var i = 0; i < len; i++) {
        item = params[i].split("=");
        param[item[0]] = item[1];
    }
    return param;
}
// demo:
parseUrl("www.xuanfengge.com/js?name=xuanfeng&age=21&page=2")
// 結(jié)果
{name: "xuanfeng", age: "21", page: "2"}

4. URL參數(shù)拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @description 將傳入的url參數(shù)對象解析組裝成字符串做為queryString中的一部分
* @param {Object} params 請求參數(shù)的數(shù)組
* @param {string} cgi 請求串
* @return {String} queryString部分字符串
* @example : param1=value1&param2=value2&param3=value3......
*/
function convert_params(params, cgi){
    var paramsArray = [];
    for (var name in params) {
        if (paramsArray.length == 0) {
            cgi && cgi.indexOf('?') != -1 ? paramsArray.push("&") : paramsArray.push("?");
        }
        else {
            paramsArray.push("&");
        }
        paramsArray.push(name);
        paramsArray.push("=");
        paramsArray.push(params[name]);
    }
    return paramsArray.join("");
}
console.log(convert_params({"param": "value1", "param2": "value2"}, "/cgi-bin/"));
// ?param=value1&param2=value2
console.log(convert_params({"param": "value1", "param2": "value2"}, "/cgi-bin/?page=1"));
// &param=value1&param2=value2

5. 判斷一個對象是否為空對象

1
2
3
4
5
6
7
8
function isEmptyObj(obj){
    for(var name in obj) {
        return false;
    }
    return true;
}
console.log(isEmptyObj({}));                //true
console.log(isEmptyObj({name: "ivan"}));    //false

6. 解析url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @description 解析url
* @param {String} 請求url串
* @return
* @type Object
* @example parse_url('http://www.xuanfengge.com/index?app_id=110000011')
*/
function parse_url(url){
    var host, path, search, hash, param = {};
    if(url === undefined) {
        var loc = window.location;
        host = loc.host;
        path = loc.pathname;
        search = loc.search.substr(1);
        hash = loc.hash;
    } else {
        var ret = url.match(/\w+:\/\/((?:[\w-]+\.)+\w+)(?:\:\d+)?(\/[^\?\\\"\'\|\:<>]*)?(?:\?([^\'\"\\<>#]*))?(?:#(\w+))?/i) || [];
        host = ret[1];
        path = ret[2];
        search = ret[3];
        hash = ret[4];
    }
    search && function() {
        var arr = search.split('&');
        for(var i = 0, l = arr.length; i < l; i++) {
            //var p=arr[i].split('=');
            //param[p[0]]=p[1];
            if(arr[i].indexOf('=') != -1) {
                var pos = arr[i].indexOf('=');
                var k = arr[i].slice(0, pos);
                var v = arr[i].slice(pos + 1);
                param[k] = v;
            }
        }
    }();
    return {
        host : host,
        path : path,
        search : search,
        hash : hash,
        param : param
    }
}
console.log(JSON.stringify(parse_url("http://www.xuanfengge.com/index?app_id=110000011")));
// {"host":"www.xuanfengge.com","path":"/index","search":"app_id=110000011","param":{"app_id":"110000011"}}

7. cookie存儲的工具類函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var cookie = {
    getTopDomain : function() {
        var top = window.location.host, list = {
            'com.cn' : 1,
            'net.cn' : 1,
            'gov.cn' : 1,
            'com.hk' : 1
        }, arr = top.split('.');
        //配置最常用的地區(qū)域名名單
        arr.length > 2 && function() {
            top = (list[arr.slice(-2).join('.')] ? arr.slice(-3) : arr.slice(-2)).join('.');
        }();
        return top;
    },
    get : function(key) {
        var ret = document.cookie.match(new RegExp("(?:^|;\\s)" + key + "=(.*?)(?:;\\s|$)"));
        return ret ? ret[1] : "";
    },
    save : function(key, value, expires) {
        document.cookie = key + "=" + value + ";path=/;domain=" + this.getTopDomain() + ( expires ? ";expires=" + expires : '');
    }
}

8. 瀏覽器及版本

1
2
3
4
5
6
7
8
var userAgent = navigator.userAgent.toLowerCase();
$.browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    safari: /webkit/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

9. 類型轉(zhuǎn)換函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var Converter = {
    toInt: function(val){
        return result = isNaN(val)? 0 : parseInt(val);
    },
    toFloat: function(val){
        return result = isNaN(val)? 0 : parseFloat(val);
    },
    toDate: function(strDate){
        var sDate = strDate.replace(/(^\s+|\s+$)/g,''); //去兩邊空格;
        if(sDate==''){
            return null;
        }
        var s = sDate.replace(/[\d]{4,4}[\-/]{1}[\d]{1,2}[\-/]{1}[\d]{1,2}/g, '');
        if (s == '')
        {
            var t=new Date(sDate.replace(/\-/g,'/'));
            var ar = sDate.split(/[-/:]/);
            if(ar[0] == t.getFullYear() && ar[1] == t.getMonth() + 1 && ar[2] == t.getDate())
            {
                return t;   //返回轉(zhuǎn)化成功的日期對象
            }
        }
        return null;
    }
};
console.log(Converter.toInt("12.3"));
// 12
console.log(Converter.toFloat("12.36"));
// 12.36
console.log(Converter.toDate("2014/9/2"));
console.log(Converter.toDate("2014-9-2"));
console.log(Converter.toDate("2014-09-02"));
// Tue Sep 02 2014 00:00:00 GMT+0800 (中國標(biāo)準(zhǔn)時間)

10. 全屏遮罩層

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* @description 全屏遮罩層管理器
* @example mask.create();
*/
var mask = {
    self : '',
    isIE6 : $.browser.msie && $.browser.version < 7,
    create : function() {
        if(this.self && this.self.parent().length) {
            return;
        }
        $(window).bind('resize.overlay', this.resize);
        return (this.self = (this.self || $('<div></div>').css({
            height : '100%',
            left : 0,
            position : 'absolute',
            top : 0,
            width : '100%',
            background : '#000',
            'opacity' : 0.3,
            'z-index' : 2001
        })).appendTo('body').css({
            width : this.width(),
            height : this.height()
        }));
    },
    destroy : function() {
        if(this.self && !this.self.parent().length) {
            return;
        }
        $([document, window]).unbind('resize.overlay');
        this.self.animate({
            opacity : 'hide'
        }, function() {
            $(this).remove().show();
        });
    },
    resize: function() {
        var _mask = mask;
        _mask.self.css({
            width: 0,height: 0
        }).css({
            width: _mask.width(),height: _mask.height()
        });
    },
    height : function() {
        var scrollHeight, offsetHeight;
        if(this.isIE6) {
            scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
            offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);
            if(scrollHeight < offsetHeight) {
                return $(window).height() + 'px';
            } else {
                return scrollHeight + 'px';
            }
        } else {
            return $(document).height() + 'px';
        }
    },
    width : function() {
        var scrollWidth, offsetWidth;
        if(this.isIE6) {
            scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
            offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
            if(scrollWidth < offsetWidth) {
                return $(window).width() + 'px';
            } else {
                return scrollWidth + 'px';
            }
        } else {
            return $(document).width() + 'px';
        }
    }
}
// demo
mask.create();
setTimeout(function(){
    mask.destroy()
}, 1000);
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號