使用HTML和jQuery的水印文本框

时间:2013-02-27 07:42:35

标签: jquery html5 watermark

我想使用HTML和jQuery创建一个水印文本框但问题是当我转到另一个页面并再次返回水印文本框页面时,水印文本以普通文本显示。

以下是我的jQuery代码:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">

    (function ($) {
        $.fn.extend({
            inputWatermark: function () {
                return this.each(function () {
                    // retrieve the value of the ‘placeholder’ attribute
                    var watermarkText = $(this).attr('placeholder');
                    var $this = $(this);
                    if ($this.val() === '') {
                        $this.val(watermarkText);
                        // give the watermark a translucent look
                        $this.css({ 'opacity': '0.65' });
                    }



                    $this.blur(function () {
                        if ($this.val() === '') {
                            // If the text is empty put the watermark
                            // back

                            $this.val(watermarkText);
                            // give the watermark a translucent look
                            $this.css({ 'opacity': '0.65' });
                        }
                    });



                    $this.focus(function () {
                        if ($this.val() === watermarkText) {
                            $this.val('');
                            $this.css({ 'opacity': '1.0' });
                        }
                    });
                });
            }
        });

    })(jQuery);
</script>

这是我的HTML代码:

<body>
<input id="input1" placeholder="Placeholder here..." />
<input id="input2" placeholder="2nd Placeholder" />
<a href="../../back.htm">google</a>
<script type="text/javascript">

    $(document).ready(function () {
        $(':input').inputWatermark();
    });

</script></body>

1 个答案:

答案 0 :(得分:1)

尝试改变:

if ($this.val() === '') {

var txtVal = $.trim( $this.val() );
if ( txtVal === '') {

添加颜色,如

...
$this.css({ 'opacity': '0.65' });
$this.css({ 'color': '#a8a8a8' });