Input with Watermark (css & Jquery)

后端 未结 3 1990
你的背包
你的背包 2020-12-06 01:36

JS

$(document).ready(function () {
    $(\":input[data-watermark]\").each(function () {
        $(this).val($(this).attr(\"data-watermark\"));
        $(th         


        
相关标签:
3条回答
  • 2020-12-06 02:13

    Your desired behaviour of "Input with Watermark" has already been done - it's called the placeholder attribute. It works in modern browsers.

    For older browsers, you should use a jQuery plugin to emulate placeholder for you.

    Lastly, to set the colour, you need CSS similar to this:

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

    Unfortunately, you can't combine the above rules; it won't work.

    0 讨论(0)
  • 2020-12-06 02:14

    Don't override existing value's

    I'll had a small problem with this nice solution, but with a little change solved, like to share it.

    Just add the if statement on line 3 to prevent override loaded value's.

    $(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
            }
        })
    });
    

    Hope it's useful.

    0 讨论(0)
  • 2020-12-06 02:23
    $(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");
                }
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题