我有一个输入字段用于在网页中输入密码:
<input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" />
Run Code Online (Sandbox Code Playgroud)
在初始状态下,用户应将"密码"作为初始值读取,当他开始输入密码时,该字段应更改为键入密码.此外,当他将其设置为空白或初始值时,该字段应将类型更改为"文本"并显示密码.
我编写了代码,让它可以在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;
}
}
Run Code Online (Sandbox Code Playgroud)
这在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>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
$('input')
.focus(function() {
$(this).css('background-color', 'white');
})
.blur(function() {
if($.trim($(this).val()) == '') {
$(this).css('background-color', 'transparent').val('');
}
});
Run Code Online (Sandbox Code Playgroud)
CSS
input {
background-color: transparent;
padding: 2px;
}
label {
color: gray;
padding: 2px 4px;
position: absolute;
z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)
现场演示: http ://jsfiddle.net/rjkf4/
| 归档时间: |
|
| 查看次数: |
15661 次 |
| 最近记录: |