随着用户体验的深入,很多网站中输入框都开始添加提示语,
由于html4没有提供这个功能,大家想出了很多方法,比较简单是写一个函数修改input的内容,初始设为提示,foucs时间就清空,当blur的时候再看内容是否为空,若为空就设为提示。
这个方法有个问题,就是表单提交的时候提示也会被提交。于是有人就在表单submit的时候加上检查input是否为提示。
这还有个问题,就是用户的输入绝对不能和提示一样。为了避免这个问题用另外的一个element放置提示,把这个element放到input的上方,显示和隐藏的逻辑基本一样。
从html5开始我们就不用那么痛苦了,@placeholder就轻松搞定:
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/