我有一个电子邮件表单文本框,当它为空时,我希望它的值为“电子邮件”,当您点击它时,文本消失。如果有人点击它并没有输入文本,在失去焦点时,我希望它返回到默认文本。
我已经尝试了一些方法,但没有任何作用。请问有谁能指点我正确的方向吗?
我有一个电子邮件表单文本框,当它为空时,我希望它的值为“电子邮件”,当您点击它时,文本消失。如果有人点击它并没有输入文本,在失去焦点时,我希望它返回到默认文本。
我已经尝试了一些方法,但没有任何作用。请问有谁能指点我正确的方向吗?
或者你可以直接使用HTML5的占位符属性:
<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" />
它大概是这样的
$('#yourElement').focus(function(){
//Check val for email
if($(this).val() == 'E-Mail'){
$(this).val('');
}
}).blur(function(){
//check for empty input
if($(this).val() == ''){
$(this).val('E-Mail');
}
});
您可以使用占位符属性,然后使用此jQuery作为IE的备用方案。
<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/>
$(document).ready(function () {
$('.watermark').focus(function () {
if ($(this).val() == $(this).attr('placeholder')) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
}
});
});
这很简单。只需删除onfocus
的值,然后(如果该值仍为空)在onblur
中重新填充它。
function slightLabel(input, text) {
jQuery(input).val(text);
jQuery(input).data('defaultText', text);
jQuery(input).focus(function(){
if(!jQuery(this).data('touched'))
{
jQuery(this).data('touched', true);
jQuery(input).val('');
}
});
// the part to restore the original text in
jQuery(input).blur(function(){
if(jQuery(this).val() == '')
{
jQuery(this).val(jQuery(this).data('defaultText'));
}
});
}
$.fn.watermark = function (c, t) {
var e = function (e) {
var i = $(this);
if (!i.val()) {
var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
i.replaceWith($c);
$c.focus(function () {
$c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
})
.change(function (e) {
i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
})
.closest('form').submit(function () {
$c.replaceWith(i);
});
}
};
return $(this).live('blur change', e).change();
};
将输入文本框的类设置为水印,即可在jquery中调用。
<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
title="Type keyword here" />
标题是将显示在水印中的内容。