基于js 的自动提示控件

最近在工作中需要自动提示的功能,本身单独的这个控件来开发难度不是很大,特别是针对项目需求对应的单一功能,但是为了让开发出的控件可以随意使用,动态配置,那么这就需要一定的时间来开发了。

先说一下我们这个自动提示的功能的要求,在input控件中输入一些值,在对应的下方会有对应合适的选项,类似百度自动提示的功能。我的这个控件为了可以在很多地方可以不做修改的进行引入,所以支持方法配置,样式配置,不需要任何其他js库,使用ajax实现等功能,在调用的时候只需一个div 给出对应的id和方法名就可以的,还可进行其他样式的配置。源代码不是很长,实现的功能也不够完善。

下面给出一个实例:

<!doctype html>
<html lang="en">
	<head>
		<script type="text/javascript" src="js/magusauto.js">
</script>
	</head>
	<body>
		<div id="magusauto" method="*.trend"></div>
	</body>
</html> 

这个html文件简单到不是程序员都可以看懂了。 最为核心的地方就是

<div id="magusauto" method="*.trend"></div>  

其中 id不可变,js要根据这个id找到对应的div,然后在其后面添加控件,method 是可配置的。对应后台调用的action ,返回结构是使用‘|’进行分割的字符串。

下面给出js源码:

/**
 * Created by se7en on 2015-06-02.
 * 
 *	控件是为了实现类似于百度自动提示的功能
 * 
 * 为了实现可重用,控件提供样式美化,参数可配置数据自动获取
 */

// ********************** 显示隐藏Tip层 *******************************//
var _key;

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

String.prototype.replaceAll = function(pattern,str)
{
	return this.replace(new RegExp(pattern, "gm"), str);
};

function ShowTip()
{
	document.getElementById(MagusObject.tipId).onmouseleave = function()
	{
		document.getElementById(MagusObject.tipId).style.display = "none";
	}

	document.onclick = function()
	{
		document.getElementById(MagusObject.tipId).style.display = "none";
	}

	document.getElementById(MagusObject.valueId).ondblclick = function(e)
	{
		_key = (e == null) ? event.keyCode : e.which
		if (_key != 39 && _key != 40 && _key != 37 && _key != 38 && _key != 13
				&& _key != 17)
		{
			document.getElementById(MagusObject.tipId).style.display = "";
			document.getElementById(MagusObject.tipId).innerHTML = " 正在获取提示...";
			VCreateAjax(MagusObject.method, BackArray, "KeyWord="
					+ document.getElementById(MagusObject.valueId).value);
		}
	}

	document.getElementById(MagusObject.valueId).onkeyup = function(e)
	{
		_key = (e == null) ? event.keyCode : e.which
		if (_key != 39 && _key != 40 && _key != 37 && _key != 38 && _key != 13
				&& _key != 17)
		{
			document.getElementById(MagusObject.tipId).style.display = "";
			document.getElementById(MagusObject.tipId).innerHTML = " 正在获取提示...";
			// 类似ajax的一个方法
			VCreateAjax(MagusObject.method, BackArray, "KeyWord="
					+ document.getElementById(MagusObject.valueId).value);
		}
	}
	document.onkeyup = function(e)
	{
		_key = (e == null) ? event.keyCode : e.which
		if (_key == 13)
		{
			var pointnametext = document.getElementById(MagusObject.valueId).value;
			if (pointnametext && pointnametext.trim() != ""
					&& !trend_Util.checkNameRE(pointnametext.trim()))
			{
				defaultTrendGroup.addName(pointnametext.trim());
				document.getElementById(MagusObject.valueId).value = "";
			}

		}
	}
}

function HideTip()
{
	var _key;
	document.onkeyup = function(e)
	{
		_key = (e == null) ? event.keyCode : e.which
		if (_key != 39 && _key != 40 && _key != 37 && _key != 38 && _key != 13
				&& _key != 17)
		{
			document.getElementById(MagusObject.tipId).style.display = "none";
		}
	}
}

function HideTTip()
{
	document.getElementById(MagusObject.tipId).style.display = "none";
}
// ********************** 显示隐藏Tip层 ************************************* //

// ********************** Ajax初始化函数 IE7.0 **********************//
function VCreateAjax(VUrl,VBack,VVar)
{
	http_request_name = false;
	if (window.XMLHttpRequest)
	{// Mozilla, Safari,...
		http_request_name = new XMLHttpRequest();
	}
	if (window.ActiveXObject)
	{ // IE
		try
		{
			http_request_name = new ActiveXObject("Msxml3.XMLHTTP");
		} catch (e)
		{
			try
			{
				http_request_name = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e)
			{
				try
				{
					http_request_name = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e)
				{
				}
			}
		}
		if (http_request_name.overrideMimeType)
		{
			http_request_name.overrideMimeType('text/html');
		}

	}

	if (!http_request_name)
	{
		document.getElementById(MagusObject.tipId).innerHTML = "<img src='../images/Icon_warning_01.gif' border='0'> 不能创建XMLHTTP对象,请升级您的浏览器或操作系统!";
		return false;
	}
	http_request_name.onreadystatechange = VBack;
	http_request_name.open('POST', VUrl, true); // 这里用GET方法传递参数,不然会出现完成该操作所需的数据还不可使用的页面错误
	http_request_name.setRequestHeader('Content-type',
			'application/x-www-form-urlencoded');
	http_request_name.send(VVar);

}

// ********************************回调函数************************************
function BackArray()
{
	if (http_request_name.readyState == 4)
	{
		if (http_request_name.status == 200)
		{
			// 返回VCreateAjax 的URL 的Tip2.jsp的资源
			var resSource = http_request_name.responseText;
			if (resSource != "")
			{
				document.getElementById(MagusObject.tipId).innerHTML = "";
				var strSplits = resSource.split('|');
				var DIVStr = "";
				var FormatStr = "";
				var sum = strSplits.length - 1;
				var elementText = document.getElementById(MagusObject.valueId).value;
				// 搜索有内容
				if (sum > 1)
				{
					for (i = 1; i < sum; i++)// cut 0, and the end element
					{
						FormatStr = strSplits[i].replace(elementText,
								"<b><font color='black'>" + elementText
										+ "</font></b>")
						DIVStr += "<div id='"
								+ i
								+ "' hideFocus style='cursor:pointer;line-height:20px;' οnmοusemοve='FocusOP("
								+ i + "," + sum + ");' οnmοuseοut='UFocusOP("
								+ i + ");' οnclick='ClickInner(\""
								+ strSplits[i] + "\");'>" + FormatStr
								+ "</div>";
					}

					document.getElementById(MagusObject.tipId).innerHTML = DIVStr;

					var i = 1;
					maxid = strSplits.length - 2;

					FocusOP(i, maxid);
					document.onkeydown = function(e)
					{
						_key = (e == null) ? event.keyCode : e.which
						// ///向下
						if (_key == 39 || _key == 40)
						{
							UFocusOP(i);
							i = i + 1;
							if (i > maxid)
							{
								i = 1;
							}
							FocusOP(i, maxid);
						}

						// ///向上
						else if (_key == 37 || _key == 38)
						{
							UFocusOP(i);
							i = i - 1;
							if (i < 1)
							{
								i = maxid;
							}
							FocusOP(i, maxid);
						}
						// 回车且弹出框显示有内容
						if (_key == 13
								&& document.getElementById(MagusObject.tipId).style.display != "none")
						{
							if (window.XMLHttpRequest)
							{
								document.getElementById(MagusObject.valueId).value = document
										.getElementById(i).textContent;
							} else
							{
								document.getElementById(MagusObject.valueId).value = document
										.getElementById(i).innerText;
							}
							document.getElementById(MagusObject.tipId).style.display = "none";
						}
					}// end key down
				}//
			} else
			{
				// alert("无数据...");
				document.getElementById(MagusObject.tipId).style.display = "none";
			}
		} else
		{
			// alert("6");
			document.getElementById(MagusObject.tipId).innerHTML = " 找不到您想要的点!!";
		}
	}
}

// 获取焦点
function FocusOP(OPP,VNum)
{
	// 清除其它焦点
	for (M = 1; M < VNum; M++)
	{
		document.getElementById(M).focus = false;
		document.getElementById(M).style.background = "white";
	}
	document.getElementById(OPP).focus = true;
	document.getElementById(OPP).style.background = "#a9e4e9";// change to

}
// 失去焦点
function UFocusOP(EID)
{
	// alert(EID + " UFocusOP ");
	document.getElementById(EID).focus = false;
	document.getElementById(EID).style.background = "#FFFFFF";

}

// 单击注入值
function ClickInner(strValue)
{
	document.getElementById(MagusObject.valueId).value = strValue;
	document.getElementById(MagusObject.tipId).style.display = "none";
}

var MagusWidget = function()
{
	this.Init.apply(this, arguments);
};
MagusWidget.prototype =
{
	/**
	 * 初始化 控件属性
	 * @param {Object} container
	 * @param {Object} options
	 * @memberOf {TypeName} 
	 */
	Init : function(container,options)
	{
		this.containerDiv = document.getElementById(container);
		MagusObject.method = this.getMethod(container);
		MagusObject.color = this.getColor(container);
		MagusObject.width = this.getWidth(container);
		MagusObject.height = this.getHeight(container);
		MagusObject.style = this.getStyle(container);
		MagusObject.options = options != null ? options :
		{
			width : '400px', height : '200px', backgroundColor : 'lightgrey',
			fontColor : 'blue'
		}
	},

	/**
	 * 获取控件对应的method名称,用于ajax调用
	 * @param {Object} container
	 * @return {TypeName} 
	 */
	getMethod : function(container)
	{
		return document.getElementById(container).getAttribute("method");
	},

	/**
	 * 获取控件对应的颜色值
	 * 
	 * @return {TypeName} 
	 */
	getColor : function(container)
	{
		return null;
	},
	/**
	 * 获取控件的宽度
	 * @param {Object} contrainer
	 * @return {TypeName} 
	 */
	getWidth : function(container)
	{
		return document.getElementById(container).getAttribute("width");
	},
	/**
	 * 获取控件的高度
	 * @param {Object} contrainer
	 * @return {TypeName} 
	 */
	getHeight : function(container)
	{
		return document.getElementById(container).getAttribute("height");
	},

	/**
	 * 设置下拉框的样式
	 * @param {Object} container
	 * @return {TypeName} 
	 */
	getStyle : function(container)
	{
		return '';
	},

	/**
	 * 页面加载的时候进行调用 显示页面
	 * @return {TypeName} 
	 */
	View : function()
	{
		var html = '<input type="text" id="magus_value" ' + 'οnblur="javascript:setTimeout(\'HideTTip()\',300);" ' + 'οndblclick="javascript:ShowTip();" οnkeyup="javascript:if ( this.value!=\'\'){ ShowTip(); } else { HideTTip(); }" size="25" /> ' + '<div id="show"> <div id="magus_tip" name=MagusObject.tipId style="display: none" align="left"></div> </div>';
		return html;
	},

	Render : function()
	{
		var widgetDiv = document.createElement('div');
		widgetDiv.style.border = MagusObject.options.border;
		widgetDiv.style.width = MagusObject.options.width;
		widgetDiv.style.height = MagusObject.options.height;
		widgetDiv.style.cursor = 'pointer';
		widgetDiv.style.backgroundColor = MagusObject.options.backgroundColor;
		// widgetDiv.style.color=this.options.fontColor;
	widgetDiv.style.color = 'green';
	var html = this.View();
	widgetDiv.innerHTML = html;
	this.containerDiv.appendChild(widgetDiv);
}
}

/**
 * 页面加载的问题
 */
window.onload = function()
{
	var widget = new MagusWidget('magusauto',
	{
		width : '180px', height : '20px', backgroundColor : ''
	});
	/**
	 * 加载 控件
	 * @param {Object} event
	 */
	widget.Render();
	ShowTip();
};
/**
 *控件需要使用到的各种 属性
 */
var MagusObject =
{
	valueId : "magus_value", tipId : "magus_tip", method : null,
	color : "green", width : "200px", height : "40px", options : ""
}

源码也是很简单的js文件,只要有一点js基础应该都能看懂,如果有人任何疑问,欢迎留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值