【发布时间】:2012-04-19 13:01:36
【问题描述】:
我知道我可以使用placeholder="some text here...",但是如何让它在按键而不是焦点时删除文本?
是否可以使用 CSS 或如何使用 jQuery 来实现?
【问题讨论】:
标签: jquery css textbox placeholder
我知道我可以使用placeholder="some text here...",但是如何让它在按键而不是焦点时删除文本?
是否可以使用 CSS 或如何使用 jQuery 来实现?
【问题讨论】:
标签: jquery css textbox placeholder
如果您想要一个允许您轻松考虑任何默认文本值的通用解决方案,请考虑以下解决方案:
类名称为“populated-text”的所有输入将默认为它们初始化时使用的文本,如果您在字段中留下空文本,则会重置。
JavaScript:
jQuery(function ($) {
// Removes the defualt text on key press
function keyDown (e) {
var input = $(e.target);
if (input && !input.data('data-entered')) {
input.data('data-entered', true);
input.val("");
}
}
// Restore the default text if empty on blur
function blur(e) {
var input = $(e.target);
if (input && input.val() === "") {
input.data('data-entered', false);
input.val(input.data('blank-value'));
}
}
$('.populated-text').each(function () {
var input = $(this);
input.data('blank-value', input.val());
input.data('data-entered', false);
input.keydown(keyDown);
input.blur(blur);
});
});
输入示例:
<input type="text" value="Some text here..." class="populated-text">
<input type="text" value="Any default text you like" class="populated-text">
<input type="text" value="Will be used as empty" class="populated-text">
【讨论】:
这并不完美,但这里有一个像新浏览器一样的占位符的尝试:
JS--
//when the input is clicked, select it's text so the cursor doesn't start typing in the middle of your placeholder text
$('input').on('click', function () {
//by selecting the input on click we mimic the focus event
$(this).select();
}).on('keyup', function () {
//if the input is un-touched
if (this.value == '' || this.value == '[Your Name]') {
//make the input in-active
this.className = '';
//and make sure the placeholder is still showing
this.value = '[Your Name]';
} else {
//since something has been entered into the input, add the active class to make the text black
this.className = 'active';
}
});
CSS --
input {
color : grey;
}
input.active {
color : black;
}
这使得输入默认为灰色文本,当用户输入内容时,它会变为黑色。
HTML --
<input type="text" value="[Your Name]" />
这是一个演示:http://jsfiddle.net/2VfwW/
您可以将占位符添加到placeholder 属性,然后检查是否支持该属性,如果它不存在,您可以运行上面的代码,但首先将每个输入的值设为@ 的值987654326@属性:
$(function () {
//find all input elements with a placeholder attribute
$('input[placeholder]').val(function () {
//set the value of this input to the value of its placeholder
return $(this).attr('placeholder');
});
});
【讨论】:
jQuery 中类似下面的东西应该可以工作。
$('#myElement').keypress(function() { this.val = ''; }
【讨论】:
使用 Javacript:
<input type="text" onfocus="if(this.value == 'Your text'){this.value=''}" value='Your text' />
【讨论】:
如果您在文本字段中有值,并且希望仅在用户在文本字段中输入键时清除它,您可以这样做:
$("#myTextfield").keypress(function() {
$(this).val("");
});
下一位检查用户是否在文本字段中输入了任何内容;如果没有,在它失去焦点时添加一个占位符。
$("#myTextfield").blur(function() {
if($(this).val() === "") {
$(this).val("Search...");
}
});
【讨论】: