$("#s")
.val("Search...")
.css("color", "#ccc")
.focus(function(){
$(this).css("color", "black");
if ($(this).val() == "Search...") {
$(this).val("");
}
})
.blur(function(){
$(this).css("color", "#ccc");
if ($(this).val() == "") {
$(this).val("Search...");
}
});
- 将字段的值设置为“Search…”
- 当字段获得焦点时,将颜色设置为黑色。
- 如果值为默认值,则将其删除。
- 当字段失去焦点时,将颜色恢复为浅灰色。
- 如果值为为空,则将默认值放回
我希望文本只有在它是默认的“search…”文本时才会变回灰色。
blur(function(){
if ($(this).val() == "") {
$(this).css("color", "#ccc");
$(this).val("Search...");
}
我认为这个更好,它适用于所有文本框,并且使用页面内的值而不是在 jQuery 中声明值。
swap_val = [];
$(".swap").each(function(i){
swap_val[i] = $(this).val();
$(this).focusin(function(){
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}
});
});
是的,不错。但这个解决方案中有一些令人不安的地方。想象一个返回错误的输入字段(例如,您必须填写的电子邮件字段)。当它提示您更正输入时,所有字段将在获得焦点时被清除……我说的对吗?
这太完美了,让我开心了一整天!谢谢。
为什么它在我的机器上不能正常工作?
这是我的页面
请看一下,我快疯了
http://www.athenarestauri.com/prova-jquery-2.html
您需要将 jQuery 函数放在
$(document).ready(function(){
// 执行 jQuery 操作
})
@Dyllon
$(“#searchfield”)
.val(“Search…”)
.css(“color”, “#999”)
.focus(function(){
$(this).css(“color”, “black”);
if ($(this).val() == “Search…”) {
$(this).val(“”);
}
})
.blur(function(){
$(this).css(“color”, “#999”);
if ($(this).val() == “”) {
$(this).val(“Search…”);
}else if($(this).val() != “Search…”){
$(this).css(“color”, “black”);
}
});
你好,我是 jQuery 的新手!
抱歉我理解错误,我知道这在 JavaScript 中可以很简单地实现,就像这样
这样是不是简单很多?