我试图让默认值不在点击时消失,而是在用户开始输入时消失(这样他们就知道该字段的用途)......问题如下:
当我使用 onchange 而不是 onfocus 时,当他们开始输入时它会保留默认值。如果它混淆了我正在做的事情,请去 Facebook 看看他们的搜索框是如何工作的……这就是我要做的。
<script>
function uFocus() {
$('#fakeusername').hide();
$('#username').show();
$('#username').focus();
}
function uBlur() {
if ($('#username').attr('value') == '') {
$('#username').hide();
$('#fakeusername').show();
}
}
</script>
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text' name='fakeusername' id='fakeusername' value=' Username' onfocus='uFocus()' />
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' />
最佳答案
两种选择:
在 HTML5 中,placeholder
属性将模拟您想要的内容,而无需 Javascript。
<input type='text' name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' />
第二种,我相信 Facebook 使用的方法是将包含示例文本的背景图像替换为空白图像。因此,您可以创建两个背景图像(第一个包含输入使用的字体中的“键入您的用户名”字样,第二个为空白)并将它们设置为在输入聚焦时翻转。
关于javascript - 使用 jquery 在键入时更改表单的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649223/