【问题标题】:Follow up question about input focus and blur跟进关于输入焦点和模糊的问题
【发布时间】:2009-12-15 14:18:39
【问题描述】:

我今天已经问了一个问题:This one

现在我有一个可以工作的代码,但只能在 FF(完全)和部分在 IE(7 和 8)中工作。

function replaceT(obj){
     var newO=document.createElement('input');
     newO.className = obj.className;
     newO.style.width = '118px';
     newO.style.height = '17px';
     newO.style.color = '#666';
     newO.setAttribute('maxlength','30');
     newO.setAttribute('type','password');
     newO.setAttribute('onblur','this.value=\'Password\'; this.type=\'text\'');
     newO.setAttribute('onfocus','this.value=\'\'; this.type=\'password\'');
     newO.setAttribute('tabindex','2');
     newO.setAttribute('value','');
     newO.setAttribute('id','password_property_input');
     newO.setAttribute('name',obj.getAttribute('name'));
     obj.parentNode.replaceChild(newO,obj);
     newO.focus();
}

在 Firefox 中一切正常,我将此函数称为焦点,因此我的旧类型密码输入变为类型文本输入。

现在,当我在此输入之外单击时(onblur),字段类型再次更改为文本,值恢复为密码。如果再次单击该字段(onfocus),我的文本类型输入再次变为密码并且值返回到''。

这在 FF 中完美运行,但在 IE 中不起作用,当我说无时,我的意思是 onblur 和 onfocus。从文本到密码输入的第一次更改有效。谢谢大家的解答

我找到了更好的解决方案,但它在 IE 中也不起作用:

window.load函数里面放:

applyPasswordType(document.getElementById('password_property_input'), 'Password', 'text');

还有函数本身..

function applyPasswordType(elem, val, typ) {
      elem.value = val;
      elem.type = typ;
      elem.onfocus = function() {
        if(this.value == val) {
          this.style.color = '';
          this.type = 'password'; //If in focus, input type will be 'password'
          this.value = '';
        }
      }

      elem.onblur = function() {
         if(this.value == '') {
           this.value = val;
           this.type = 'text'; //On blur, input type will be 'text' in order to show value
         }
       }
     }

我还在想办法用 addeventlistener 解决这个问题..

【问题讨论】:

    标签: javascript internet-explorer


    【解决方案1】:

    setAttribute在IE里坏了,别用了。

    直接使用属性:

    foo.onevent = function () { ... }
    

    更好的是,使用addEventListener/attachEvent

    您可能还会发现 IE 无法更改现有输入的类型。如果是这样,您必须创建一个新输入并替换现有输入。

    【讨论】:

    • 所以我应该每次在 IE 中替换输入?有办法解决吗?我的意思是另一种方法来处理我正在尝试做的事情的整个大局。我希望我的密码具有“密码”值,并且当专注于使用密码屏蔽更改为真实密码字段时,还可以使用 onblur 恢复密码字段的密码值。
    • 你能否澄清一下“foo.onevent = function () { ... }”部分我不知道你在说什么(我的错)。谢谢
    • 我可以澄清 onevent = stuff ... 但有关 addEventListner/attachEvent 的链接文章是更好的解决方案。
    • 至于更好的解决方案,如果我退后一步看看问题——停止滥用 value 属性作为标签。使用<label> 元素作为标签。 (如果你真的想变得聪明一点,那就试着把标签放在输入下面。请参阅dorward.me.uk/tmp/label-work/example.html 以获取 未完成 示例)
    • +1,两个钉子都打在头上。 @c0mrade:回复setAttribute和事件,大卫指的是webbugtrack.blogspot.com/2007/08/…至于不能改变现有输入的类型,大卫指的是universalwebservices.net/web-programming-resources/javascript/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多