我有一个用于在网页中输入密码的输入字段:
<input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" />
在初始状态下,用户应该读取“密码”作为初始值,当他开始输入密码时,该字段应该更改为输入密码。此外,当他将其设置回空白或初始值时,该字段应将类型更改为“文本”并显示密码。
我编写代码并使其在 Firefox、Chrome 和 safari 上运行,并且在 IE 8 上不会将类型更改为密码。
这是我通过编辑现有功能代码制作的js代码:
function txtOnFocus2(elementId, defaultText)
{
if (document.getElementById(elementId).value == defaultText)
{
document.getElementById(elementId).value = "";
document.getElementById(elementId).type = "password";
}
}
function txtOnBlur2(elementId, defaultText)
{
var textValue = document.getElementById(elementId).value;
if (textValue == defaultText || textValue.length == 0)
{
document.getElementById(elementId).type = "text";
document.getElementById(elementId).value = defaultText;
}
}
这在 Firefox、chrome 和 safari 中运行良好,但在 IE 8 上不会更改字段类型。
最佳答案
另一种解决方案是完全改变您的方法。以下技术可以优雅地降级,更易于访问,并且对 JavaScript 的依赖性更低:
HTML
<div><label for="email">Email</label> <input type="text" name="email" id="email" /></div>
<div><label for="password">Password</label> <input type="password" name="password" id="password" /></div>
JavaScript
$('input')
.focus(function() {
$(this).css('background-color', 'white');
})
.blur(function() {
if($.trim($(this).val()) == '') {
$(this).css('background-color', 'transparent').val('');
}
});
CSS
input {
background-color: transparent;
padding: 2px;
}
label {
color: gray;
padding: 2px 4px;
position: absolute;
z-index: -1;
}
关于Javascript 动态更改输入类型在 IE8 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618306/