⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 func.js

📁 类似163BBS的代码,大家可以参考一些
💻 JS
📖 第 1 页 / 共 2 页
字号:
////////////////////////////////////////////////////////////////////////
// Shared Function Library v2.5.1
// 2007-03-14 12:17:11
// SiC
////////////////////////////////////////////////////////////////////////

//**********************************************************
// Core Functions
//**********************************************************


//----------------------------------------------------------
// Clone an object/array
//----------------------------------------------------------
// Never use the Object.prototype to pollute Object data array
function $clone(obj){

	if(typeof obj != "object") return obj;

	var newObj;

	if(obj instanceof Array){
		// Clone Array
		newObj = [];
		for(var i=0; i<obj.length; i++){
			if(typeof obj[i] == "object"){
				newObj[i] = $clone(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}else{
		// Clone Object
		newObj = {};
		for(i in obj){
			if(typeof obj[i] == "object"){
				newObj[i] = $clone(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}

	return newObj;

}


//----------------------------------------------------------
// Extend an object if property not exist yet
//----------------------------------------------------------
function $extend(objTarget, objAdd, forceOverride){

	var obj = $clone(objTarget); // always new, no pollution

	if(typeof obj != "object") return obj;

	for(var item in objAdd){
		if(obj[item] == undefined || forceOverride) obj[item] = objAdd[item];
	}

	return obj;

}


//----------------------------------------------------------
// Convert Object to JSON String
//----------------------------------------------------------
function $toJSON(obj, param){

	// paramters
	var defaultParam = {
		'indent': 0,
		'indentText': '',
		'delimiter': '',
		'includeFunction': false
	};

	param = param ? $extend(param, defaultParam) : defaultParam;

	//execute
	var indentString = '';
	var prevIndentString = '';

	if(param['indentText'] != ''){
		param['indent']++;
		prevIndentString = new Array(param['indent']).join(param['indentText']);
		indentString = new Array(param['indent']+1).join(param['indentText']);
	}

	switch(typeof(obj)){

		case "object":

			if(obj instanceof Array){

				var out = [];
				for(var i=0; i<obj.length; i++){
					var t = $toJSON(obj[i], param);
					if(t){
						out.push(indentString + t);
					}
				}

				out = "[" +
					param["delimiter"] +
					out.join("," + param["delimiter"]) +
					param["delimiter"] +
					prevIndentString + "]";

			}else if(obj instanceof Date){

				return "new Date(" +
					obj.getFullYear() + "," + obj.getMonth() + "," + obj.getDate() + "," +
					obj.getHours() + "," + obj.getMinutes() + "," + obj.getSeconds() + "," + obj.getMilliseconds() +
					")";

			}else if(obj instanceof Object){

				var out = [];
				for(label in obj){
					var l = $toJSON(label);
					var t = $toJSON(obj[label], param);
					if(t){
						out.push(indentString + l + ": " + t);
					}
				}

				out = "{" +
					param["delimiter"] +
					out.join("," + param["delimiter"]) +
					param["delimiter"] +
					prevIndentString + "}";

			}

			break;

		case "string":

			var str = obj;
			str = str.replace(/\\"/g, '\\\\"');
			str = str.replace(/\r/g, '\\r');
			str = str.replace(/\t/g, '\\t');
			str = str.replace(/\n/g, '\\n');
			str = str.replace(/\f/g, '\\f');
			str = str.replace(/\"/g, '\\"');

			out = '"' + str + '"';
			break;

		case "number":

			out = isFinite(obj) ? String(obj) : 'null';
			break;

		case "boolean":

			out = obj.toString();
			break;

		case "function":

			if(param["includeFunction"]){
				out = obj.toString();
			}else{
				out = '';
			}

			break;

		case "null":

			out = "null";
			break;
	}

	return out;

}


//----------------------------------------------------------
// Convert JSON String to Object
//----------------------------------------------------------
function $fromJSON(jsonString){

	var obj;

	try{
		obj = eval("(" + jsonString + ")");
	}catch(e){
		obj = null;
	}

	return obj;

}


//----------------------------------------------------------
// Debug functions
//----------------------------------------------------------
function $dump(obj){

	alert(
		$toJSON(
			obj,
			{
				"indentText": '  ',
				"delimiter": "\n"
			}
		)
	);

}


//**********************************************************
// String Functions
//**********************************************************


//----------------------------------------------------------
// Repeat a string
//----------------------------------------------------------
String.prototype.$repeat = function(times){

	return new Array(times + 1).join(this);

}


//----------------------------------------------------------
// Trim a string
//----------------------------------------------------------
String.prototype.$trim = function(){

	return this.replace(/^[\s\n\t]*|[\s\n\t]*$/g, "");

}


//----------------------------------------------------------
// Get the char font width - detect Unicode Wide char
//----------------------------------------------------------
String.prototype.$charWidthAt = function(index){

	// paramters
	if(this.length < 1) return 0;
	if(!index) index = 0;

	// execute
	var charCode = this.charCodeAt(index);

	// Control Chars
	if(charCode < 32){
		return 0;
	}

	// Wide chars
	if(
		(charCode >= 0x1100 && charCode <= 0x115F)
		|| (charCode == 0x2329 || charCode == 0x232A)
		|| (charCode >= 0x2E80 && charCode <= 0x303E)
		|| (charCode >= 0x3041 && charCode <= 0x4DB5)
		|| (charCode >= 0x4E00 && charCode <= 0xA4C6)
		|| (charCode >= 0xAC00 && charCode <= 0xDFFF)
		|| (charCode >= 0xF900 && charCode <= 0xFAD9)
		|| (charCode >= 0xFE10 && charCode <= 0xFE19)
		|| (charCode >= 0xFE30 && charCode <= 0xFE6B)
		|| (charCode >= 0xFF01 && charCode <= 0xFF60)
		|| (charCode >= 0xFFE0 && charCode <= 0xFFEE)
		){
		return 2;
	}

	// Normal
	return 1;

}


//----------------------------------------------------------
// Cut a string for display - Unicode Wide char supported
//----------------------------------------------------------
String.prototype.$cut = function(length, param){

	// paramters
	var defaultParam = {
		'addPoints': true,
		'pointsText': '...',
		'reverse': false
	};

	param = param ? $extend(param, defaultParam) : defaultParam;

	// execute
	var result = this.valueOf();
	var realLength = 0;

	if(!param['reverse']){

		for(var i=0; (realLength<=length) && (i<this.length); i++){
			realLength += this.$charWidthAt(i);
		}

		result = result.substring(0, i);

	}else{

		for(var i=this.length-1; (realLength<=length) && (i>-1); i--){
			realLength += this.$charWidthAt(i);
		}

		result = result.substring(result.length - i, result.length);

	}

	if(param['addPoints'] && result.length != this.length){
		if(!param['reverse']){
			result += param['pointsText'];
		}else{
			result = param['pointsText'] + result;
		}
	}

	return result;

}


//----------------------------------------------------------
// HTML Encode
//----------------------------------------------------------
String.prototype.$encodeHTML = function(isTextArea){

	// execute
	var result = this.valueOf();
	result = result.replace(/\&/g, "&amp;");
	result = result.replace(/\>/g, "&gt;");
	result = result.replace(/\</g, "&lt;");
	result = result.replace(/\"/g, "&quot;");
	result = result.replace(/\'/g, "&#39;");

	if(!isTextArea) result = result.replace(/\n/g, "<br/>");

	return result;

}


//----------------------------------------------------------
// Remove HTML Tags
//----------------------------------------------------------
String.prototype.$stripHTML = function(){

	// execute
	var result = this.valueOf();
	result = result.replace(/\<[^\<\>]+\>/g,"");
	result = result.replace(/ +/g," ");
	result = result.replace(/\n+/g,"\n");

	return result;

}


//----------------------------------------------------------
// Sanitize HTML - Remove Malicious HTML Codes
//----------------------------------------------------------
String.prototype.$sanitizeHTML = function(arrAllowedTags){

	// parameters
	if(arrAllowedTags == undefined){
		arrAllowedTags = {
			"br": {},
			"b": {},
			"strong": {},
			"u": {},
			"em": {},
			"ul": {},
			"ol": {},
			"li": {},
			"blockquote": {
				"style": {invalid: "expression|script"}
			},
			"p": {
				"align": {valid: "left|center|right"},
				"style": {invalid: "expression|script"}
			},
			"span": {
				"style": {invalid: "expression|script"}
			},
			"div": {
				"align": {valid: "left|center|right"},
				"style": {invalid: "expression|script"}
			},
			"a": {
				"href": {valid: "^(http|https|ftp|mailto)\:"},
				"title": {},
				"target": {}
			},
			"img": {
				"src": {valid: "^(http|ftp):"},
				"alt": {}
			}
		};
	}


	// execute
	var result = this.valueOf();

	result = result.replace(/[\x00-\x1f\x7f]/ig, "");

	// Loop through all open tags
	var re = /\<([^\/].*?)(\/)?\>/ig;
	while( (arrMatch = re.exec(result)) != null){

		// Process Tags
		var sourceLength = arrMatch[1].length;
		var arrParts = arrMatch[1].split(" ");
		var targetString = "";

		for(var item in arrAllowedTags){

			// Check for Allowed Tags
			var tagName = arrParts[0];
			if(arrAllowedTags[tagName]){

				// Allowed Tags
				for(var i=1; i<arrParts.length; i++){

					// Check for attributes
					var pos = arrParts[i].indexOf("=");
					if(pos<1){

							// Not Found - Remove it
							arrParts.splice(i, 1);
							i--;

					}else{

						// Found
						var attrName = arrParts[i].substr(0, pos);
						var attrValue = arrParts[i].substr(pos+1, arrParts[i].length);

						// Remove quotes and encode inside content
						if(attrValue.indexOf('"')==0 || attrValue.indexOf("'")==0){
							attrValue = attrValue.substr(1, attrValue.length);
							attrValue = attrValue.substr(0, attrValue.length-1);
						}

						//Check For allowed attributes
						if(arrAllowedTags[tagName][attrName]){

							// Found
							// Do Validation
							if(arrAllowedTags[tagName][attrName].valid){
								var attrRe = new RegExp(arrAllowedTags[tagName][attrName].valid, "ig");
								if(!attrRe.test(attrValue)){
									// Not Found - Remove it
									arrParts.splice(i, 1);
									i--;
									continue;
								}
							}

							//Check for invalid content
							if(arrAllowedTags[tagName][attrName].invalid){
								var attrRe = new RegExp(arrAllowedTags[tagName][attrName].invalid, "ig");
								if(attrRe.test(attrValue)){
									// Not Found - Remove it
									arrParts.splice(i, 1);
									i--;
									continue;
								}
							}

							// Re-assemble the attribute item
							attrValue = attrValue.replace(/\"/ig, "&quot;");
							arrParts[i] = attrName + '="' + attrValue + '"';

						}else{
							arrParts.splice(i, 1);
							i--;
						}

					}

				}

				targetString = "<" + arrParts.join(" ") + arrMatch[2] + ">";

			}else{

				// Forbidden Tags - Remove it
				targetString = "";

			}

		}

		// Update String
		result = result.replace(arrMatch[0], targetString);

		// Set RegExp Position
		re.lastIndex += targetString.length - sourceLength;

	}

	return result;

}


//----------------------------------------------------------
// Sanitize URL - Remove Malicious Codes
//----------------------------------------------------------
String.prototype.$sanitizeURL = function(){

	// execute
	var result = this.valueOf();

	// no special pprotocols
	var re = /^(.*?)script:/ig;
	if(re.test(result)) return "";
	re = /^about:/ig;
	if(re.test(result)) return "";

	result = result.replace(/</ig, "%3C");
	result = result.replace(/>/ig, "%3E");
	result = result.replace(/ /ig, "%20");

	return result;

}


//----------------------------------------------------------
// Safe string parameter value for tag attributes
//----------------------------------------------------------
String.prototype.$safeQuote = function(bSingleQuote){

	// execute
	var result = this.valueOf();

	if(bSingleQuote){
		result = result.replace(/\'/ig, "\\\'");
	}else{
		result = result.replace(/\"/ig, "\\\"");
	}

	return result;

}

//**********************************************************
// Datetime Functions
//**********************************************************
$Date = {};
$Date.names = {};
$Date.names.weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$Date.names.weekdayAbbr = ["Sun", "Mon", "Tue", "Wedy", "Thu", "Fri", "Sat"];
$Date.names.month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
$Date.names.monthAbbr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
$Date.names.ampm = ["AM", "PM"];
$Date.names.ampmAbbr = ["A", "P"];


//----------------------------------------------------------
// Parse a yyy-mm-dd hh:ii:ss format datetime string
//----------------------------------------------------------
$Date.parse = function(strDateTime){

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -