输入水印(css和Jquery)

JS

$(document).ready(function () { $(":input[data-watermark]").each(function () { $(this).val($(this).attr("data-watermark")); $(this).bind('focus', function () { if ($(this).val() == $(this).attr("data-watermark")) $(this).val(''); }); $(this).bind('blur', function () { if ($(this).val() == '') $(this).val($(this).attr("data-watermark")); $(this).css('color','#a8a8a8'); }); }); }); 

HTML

   

CSS

 .input{ width:190px; height:16px; padding-top:2px; padding-left:6px; color:#000; font-size: 0.688em; border:#8c9cad 1px solid; } 

我想要解决的是,只要水印的输入值是文本的颜色应该是灰色的#a8a8a8 )。 当值是用户写的东西时,颜色应该是黑色

这是小提琴: http : //jsfiddle.net/qGvAf/

 $(document).ready(function () { $(":input[data-watermark]").each(function () { $(this).val($(this).attr("data-watermark")); $(this).css("color","#a8a8a8"); $(this).bind("focus", function () { if ($(this).val() == $(this).attr("data-watermark")) $(this).val(''); $(this).css("color","#000000"); }); $(this).bind("blur", function () { if ($(this).val() == '') { $(this).val($(this).attr("data-watermark")); $(this).css("color","#a8a8a8"); } else { $(this).css("color","#000000"); } }); }); }); 

您已经完成了“使用水印输入”所需的行为 – 它被称为placeholder属性 。 它适用于现代浏览器 。

对于旧版浏览器,您应该使用jQuery插件为您模拟placeholder

最后,要设置颜色,您需要类似于此的CSS:

 .placeholder { color: #a8a8a8; } ::-webkit-input-placeholder { color: #a8a8a8; } :-moz-placeholder { color: #a8a8a8; } 

不幸的是,你无法结合上述规则; 它不会起作用 。

不要覆盖现有值

对于这个不错的解决方案,我会遇到一个小问题,但是解决了一些变化,比如分享它。

只需在第3行添加if语句以防止覆盖加载的值。

 $(document).ready(function () { $('.watermark').each(function () { // add the line below if (this.value == '') { $(this).val($(this).attr("data-watermark")); $(this).css("color", "#a8a8a8"); $(this).bind("focus", function () { if ($(this).val() == $(this).attr("data-watermark")) $(this).val(''); $(this).css("color", "#000000"); }); $(this).bind("blur", function () { if ($(this).val() == '') { $(this).val($(this).attr("data-watermark")); $(this).css("color", "#a8a8a8"); } else { $(this).css("color", "#000000"); } }); // Don't forget the closing bracket } }) }); 

希望它有用。