2010-06-29 83 views
1

有一个脚本jQuery.replaceWith()的输入字段和恢复聚焦在IE

http://gist.github.com/457324

,其设定为空input[type=text]input[type=password]元素默认的文本(从元件的title属性截取)。

对于密码元素,它并不是那么微不足道。如果我为input[type=password]做了$(this).attr('value', $(this).attr('title'));,它只会显示点而不是默认文本。改变元素的类型(在这种情况下,从密码到文本)也不被广泛支持。所以唯一的方法是用input[type='text']元素替换input[type='password'](util.js:26)。这种替换似乎重置IE中的页面标签索引,并从页面的开始处开始。其他浏览器按预期行事。

我找到了类似问题的解决方案here但它不适用于我。

你有任何想法如何解决?

回答

0

我碰巧写了一个函数来完成这个今天,并找到您的文章。该函数通过使用延迟为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); 
     }); 
} 
+0

谢谢sunetos。 我已经修复它,如果你想使用它的代码是可用的jQuery插件。 http://github.com/misza222/Defaultize-jQuery-plugin – misza222 2010-07-14 10:53:08