分享原生JavaScript技巧大收集(41~50)

文章来源:jquery教程 - http://www.jq-school.com/Show.aspx?id=304

41、原生JavaScript完美判断是否为网址

function IsURL(strUrl) {
    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
    if (regular.test(strUrl)) {
        return true;
    }
    else {
        return false;
    }
}


42、原生JavaScript根据样式名称检索元素对象

function getElementsByClassName(name) {
    var tags = document.getElementsByTagName('*') || document.all;
    var els = [];
    for (var i = 0; i < tags.length; i++) {
        if (tags[i].className) {
            var cs = tags[i].className.split(' ');
            for (var j = 0; j < cs.length; j++) {
                if (name == cs[j]) {
                    els.push(tags[i]);
                    break
                }
            }
        }
    }
    return els
}


43、原生JavaScript判断是否以某个字符串开头

String.prototype.startWith = function (s) {
    return this.indexOf(s) == 0
}


44、原生JavaScript判断是否以某个字符串结束

String.prototype.endWith = function (s) {
    var d = this.length - s.length;
    return (d >= 0 && this.lastIndexOf(s) == d)
}


45、原生JavaScript返回IE浏览器的版本号

function getIE(){
    if (window.ActiveXObject){
        var v = navigator.userAgent.match(/MSIE ([^;]+)/)[1];
        return parseFloat(v.substring(0, v.indexOf(".")))
    }
    return false
}


46、原生JavaScript获取页面高度

function getPageHeight(){
	var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
			? a
			: g.documentElement;
	return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
}


47、原生JavaScript获取页面scrollLeft

function getPageScrollLeft(){
	var a = document;
	return a.documentElement.scrollLeft || a.body.scrollLeft;
}


48、原生JavaScript获取页面可视宽度

function getPageViewWidth(){
	var d = document, a = d.compatMode == "BackCompat"
			? d.body
			: d.documentElement;
	return a.clientWidth;
}


49、原生JavaScript获取页面宽度

function getPageWidth(){
	var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
			? a
			: g.documentElement;
	return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}


50、原生JavaScript获取页面scrollTop

function getPageScrollTop(){
	var a = document;
	return a.documentElement.scrollTop || a.body.scrollTop;
}

相关推荐