我希望创建一个输入文本字段,其中包含显示文本字段用途的灰色文本,然后在输入字符时删除此文本
例如在Facebook上点击搜索输入文本区域时,在输入任何字符之前,您会看到仍然显示“搜索”字样。
我不知道从哪里开始使用JQuery,因为我不知道这个功能被调用了什么,但下面是我的输入字段的标记
HTML标记
<div class="searchForm">
<input id="searchInput" value="Search" autocomplete="off" name="searchInput"
onkeyup="showResult(this.value)"/>
<input type="hidden" name="searchSite" value="1" style="background-color:#000;">
<input id="searchButton" type="submit" value=""/>
</div>
答案 0 :(得分:3)
您可以使用html 5属性placeholder
,如下所示:
<input id="searchInput" type="text" placeholder="Search" name="searchInput" />
答案 1 :(得分:2)
有几种方法可以做到这一点。使用HTML5,可以使用占位符属性轻松实现。这允许您在HTML元素中定义文本,并且在焦点上它将消失。
<input id="searchInput" value="Search" autocomplete="off" name="searchInput" placeholder="Search"
onkeyup="showResult(this.value)"/>
其他JavaScript方法是使用清除焦点或单击等文本的方法。
$('input#searchInput').focus(function() {
$(this).value('');
});
答案 2 :(得分:1)
这是来自另一个answer of mine。而this就是这段代码的例子。
HTML
<div>
<label for="search">Search this site</label>
<input type="text" id="search" value="" />
</div>
CSS
body { padding: 20px; }
div { position: relative; }
div label { position: absolute; left: 8px; top: 4px; color: #666; z-index: 2; font: 11px arial; }
div input { position: absolute; padding: 3px 6px; border: 1px solid #ddd; border-radius: 2px; z-index: 1; font: 11px arial; }
.populated label { display: none; }
.focused label { color: #aaa; }
的Javascript
$('input').on('keydown keypress keyup', function(e) {
if($('input').val() == '') {
$('div').removeClass('populated');
}
else {
$('div').addClass('populated');
}
}).on('focus', function(e) {
$('div').addClass('focused');
}).on('blur', function(e) {
$('div').removeClass('focused');
});
答案 3 :(得分:1)
如果您使用的是HTML5,则应使用placeholder
attribute。
如果您使用的是HTML4.01或XHTML1.0,请参阅此问题的最终修改:unobtrusive "default" text in input WITHOUT jQuery(最后使用jQuery)
答案 4 :(得分:1)
正如其他答案所示,我建议使用HTML 5 placeholder
属性。对于不支持此功能的浏览器,您可以按如下方式添加支持:
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
$(function() {
// add placeholder support to browsers that wouldn't otherwise support it.
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text,:password').focus(function() {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function() {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text,:password').blur();
$(active).focus();
$('form:eq(0)').submit(function() {
$(':text.hasPlaceholder,:password.hasPlaceholder').val('');
});
}
});
此代码源自此处:http://www.cssnewbie.com/example/placeholder-support/
我修改它以支持密码字段(尽管它们只显示为*)并且已成功使用它。我喜欢它,因为我只使用HTML placeholder
属性,一切都运行良好。
希望这有帮助!