文本框的框内提示

最近遇到需要做到把输入框提示放入输入框内部的需求。不是太复杂的东西,但大概正因如此,没有找到完整的方案,于是自己写了一个。

代码贴在后面,把几个需要注意的点放在前面吧。

1,主要逻辑就是focus和blur时要干点什么。

2,使用title属性保存提示信息,一来没有多余的东西,二来还可以获得一个停留时的提示。

3,因为IE的password输入框的type属性只读,所以使用show&hide的方式。虽说所有的地方都可以show&hide,但我还是偏好少点无用标记的方式。

4,form提交前必需做好清理工作,避免把提示当值给提交了(show&hide没有此问题,但会有没用的键值对)。这对新作的东西没啥影响,但改老代码,尤其是直接把事件绑在tag中的代码,要注意一下。

 

其实html5有个placeholder直接就是干这个事的,可是这还不是html5的时代。(吐槽:哪有这么好,连IE都不能不管,不然代码至少少一半。)

也考虑了一下,要不要做成JQuery的plugin,想想算了,简单的东西就简单的处理好了,真有必要了再说吧。

 

<!DOCTYPE html>
<html>
<head>
  <title>Hint in Box</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	var textFocus = function() { // for in-box hint (username, focus)
		if (this.title && this.value === this.title) this.value = '';
	};
	$('input[type="text"]').blur(function() { // for in-box hint (username, blur)
		if (!this.value) this.value = this.title;
	}).focus(textFocus);
	var fakePassword = $('#fakePassword'),
		password = $('#password');
	if (fakePassword.length === 1) { // for in-box hint (password). It's complex because ie doesn't allow changes on the type of password.
		fakePassword.focus(function() { // focus
			fakePassword.hide();
			password.show().select();
		});
		password.blur(function() { // blur
			if (!this.value) {
				password.hide();
				fakePassword.show();
			}
		}).blur(); // blur at start to ensure the hint shows.
	}
	$('form').submit(function() { // rebind submit handler to form because we need some pre work involved with in-box hint.
		$('input[type="text"]').each(textFocus); // ensure the hint is clear.
		return checkAndSubmit(); // do the original submit.
	});
	function checkAndSubmit(){
		// some code here
		return true;
	}
});
</script>
</head>
<body>
<form name="aForm" action="/something">
	<div><input type="text" id="username" name="username" title="User ID" /></div>
	<div><input type="text" id="fakePassword" name="fakePassword" value="Password" title="Password" /><input type="password" id="password" name="password" title="Password" /></div>
	<div><input type="text" id="something" name="something" title="Something..." /></div>
	<div><input type="text" id="something1" name="something1" title="" /></div>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值