跨浏览器输入框提示探讨

随着用户体验的深入,很多网站中输入框都开始添加提示语,

由于html4没有提供这个功能,大家想出了很多方法,比较简单是写一个函数修改input的内容,初始设为提示,foucs时间就清空,当blur的时候再看内容是否为空,若为空就设为提示。

这个方法有个问题,就是表单提交的时候提示也会被提交。于是有人就在表单submit的时候加上检查input是否为提示。

这还有个问题,就是用户的输入绝对不能和提示一样。为了避免这个问题用另外的一个element放置提示,把这个element放到input的上方,显示和隐藏的逻辑基本一样。

从html5开始我们就不用那么痛苦了,@placeholder就轻松搞定:


<input type="text" placeholder="Start typing to begin searching." />

firefox3.7+, chrome/safari4.0+中的效果:


用jquery测试placeholder是否可用

jQuery(function() {
	jQuery.support.placeholder = false;
	test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
});

对于其他浏览器,我们使用比较传统的方法:


$(function() {
	if(!$.support.placeholder) { 
		var active = document.activeElement;
		$(':text').focus(function () {
			if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
				$(this).val('').removeClass('hasPlaceholder');
			}
		}).blur(function () {
			if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
				$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
			}
		});
		$(':text').blur();
		$(active).focus();
		$('form').submit(function () {
			$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
		});
	}
});
 参考:http://www.cssnewbie.com/cross-browser-support-for-html5-placeholder-text-in-forms/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值