如果查看stackoverflow中的“提问”表单,则会自动选择问题输入字段。当你点击它时,整个事情就消失了,又名ToggleVal
但是,如果你使用toggleVal插件,它会自动删除.select()上的默认值,即使select()是以编程方式完成的
Stackoverflow如何阻止自动擦除?
答案 0 :(得分:3)
我查看了源代码,发现了这个:
<input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field edit-field-overlayed" value="">
<span class="edit-field-overlay">what's your programming question? be specific.</span>
基于此,这是我的假设(不看代码)。我在想他们使用span标签中的文本作为文本输入的默认值。我知道这是因为我更改了跨度中的文本(使用firebug)然后重新聚焦到字段中,它显示了我编辑的文本。无论如何,这是我很快写的东西。
// set the default value based on the span text
$('input[name=foo]').val($('.foo-overlay').text());
// whenever there is focus or blur
$('input[name=foo]').bind('focus blur',function(){
// get the default text from the span
var defaultText = $('.foo-overlay').text();
// if the input field has default text
if(this.value == defaultText){
this.value = '';
}
// if the input is blank, set it to the default text
else if (!this.value.length){
this.value = defaultText;
};
});
Here's a demo。我不是说这正是他们这样做的原因。这是基于简短介绍的推测。
修改
重新阅读您的问题,并意识到您可能会在如何不删除默认值之后?看看这个类似的演示:http://jsbin.com/oyani4/2/
这是更新后的代码:
// set the default value based on the span text
$('input[name=foo]').val($('.foo-overlay').text());
// whenever there is focus or blur
$('input[name=foo]').bind('focus blur',function(){
// if there is no length, reset to default text
if (!this.value.length){
this.value = $('.foo-overlay').text();
};
});
$('input[name=foo]').keydown(function(){
// if there is length and it's not our default text
if (this.value.length && this.value == $('.foo-overlay').text()){
this.value = '';
};
});