我碰巧写了一个函数来完成这个今天,并找到您的文章。该函数通过使用延迟为1的setTimeout()来处理密码字段交换,以便执行的下一个“帧”可以关注元素。只需从document.ready()上下文中调用watermark()即可。
/** Support outerHTML in all browsers, from http://www.briangrinstead.com/blog/jquery-outerhtml-snippet */
$.fn.outerHTML = function() {
var doc = this[0] ? this[0].ownerDocument : document;
return $('<div>', doc).append(this.eq(0).clone()).html();
};
/** Lightweight way to have subtle title instructions in text fields. */
function watermark(exclude) {
if (!exclude) exclude = '';
$('input[type="text"], input[type="password"]').each(function(){
var self = this;
function setTitle() {
if (self === document.activeElement) return; // Don't change the currently focused field
if (self.value.length == 0 && !$(self).is(exclude)) {
$(self).addClass('textLabel');
if ($(self).attr('type') == 'password') {
var newSelf = $($(self).outerHTML().replace(/type=["]?password["]?/i, 'type="text"')).get(0);
$(self).replaceWith(newSelf);
self = newSelf;
$(self).data('restorePassword', true).focus(focus).blur(blur);
}
self.value = $(self).attr('title');
}
}
setTitle();
function focus(){
if(self.value == $(self).attr('title')) {
$(self).removeClass('textLabel');
if ($(self).data('restorePassword')) {
$(self).removeData('restorePassword');
var newSelf = $($(self).outerHTML().replace(/type=["]?text["]?/i, 'type="password"')).get(0);
$(self).replaceWith(newSelf);
self = newSelf;
setTimeout(function() {$(self).focus().focus(focus).blur(blur);}, 1);
}
self.value = '';
}
}
function blur(){
setTitle();
}
$(self).focus(focus).blur(blur);
});
}
谢谢sunetos。 我已经修复它,如果你想使用它的代码是可用的jQuery插件。 http://github.com/misza222/Defaultize-jQuery-plugin – misza222 2010-07-14 10:53:08