有一个脚本
为空 input[type=text]
和 input[type=password]
元素设置默认文本(取自元素的 title 属性)。
对于密码元素来说,这并不是那么简单。如果我为 input[type=password]
执行 $(this).attr('value', $(this).attr('title'));
,它会仅显示点而不是默认文本。更改元素的类型(在本例中从密码到文本)也没有得到广泛支持。因此,唯一的方法是将 input[type='password']
替换为 input[type='text']
元素 (util.js:26)。此替换似乎重置了 IE 中的页面选项卡索引并从页面开头开始。其他浏览器的行为符合预期。
我找到了类似问题的解决方案here但这对我不起作用。
你知道如何解决这个问题吗?
最佳答案
我今天碰巧编写了一个函数来完成此任务,并找到了您的帖子。该函数通过使用延迟为 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);
});
}
关于javascript - 输入字段上的 jQuery.replaceWith() 并在 IE 中重新获得焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3141977/