扩展jQuery以使占位符像我创建的一样

Extend jQuery to make placeholder like i have created

本文关键字:一样 创建 jQuery 占位符 扩展      更新时间:2023-09-26

我在<input>字段周围创建了一个占位符:

HTML:

 <div style="position: relative;font-size: 20px;">
     <input type="text" name="username" id="lgip" style="width: 100%"  class="lgip"    value="<?php echo $username ?>" onkeyup="perform(this.value,'plcun')"/>
     <div class="placer" style="padding: 5px" onclick="$('#lgip').focus()" id="plcun">Enter UserName or Email Address</div>
 </div>

JavaScript:

function perform(val,hid){
    if(val=="") {
        $("#"+hid).show();
    } else{
        $("#"+hid).hide();
    }
}

CSS:

input.lgip{ padding: 5px;font-size: 20px;border: 1px solid #2B4EA2 }
div.placer{ position: absolute;z-index: 5;top: 0px;left: 0px;background: transparent;width: 100%;color: #cccccc;white-space: nowrap;padding: 2px;padding-left: 4px }

目前,这需要我在<input>周围添加一个外部<div>,并在其下方添加另一个<div>

我想扩展jQuery,这样它就可以为任何input:texttextarea制作一个占位符,这样当我使用类似$("#lgip").makePlacer("Enter Username Or Email");的东西时,它就会制作一个像我创建的占位符一样的占位符。

编写jQuery插件实际上相当容易。基本上,您只需将插件函数添加到jQuery.fn对象中。在插件中,您可以创建所需的HTML元素,并将它们添加到DOM中。

(function($){
    $.fn.makePlacer = function(text){
        this.each(function(){
            var e = $(this);
            if (e.is("input[type='text'], textarea")) {
                var wrapper = $("<div/>").css({position: "relative", fontSize: 20});
                var placer = $("<div/>").html(text != undefined ? text : "").css({padding: 5}).addClass("placer").click(function(){
                    e.focus();
                });
                e.wrap(wrapper);
                e.after(placer);
                e.keyup(function(){
                    e.val().length ? e.next().hide() : e.next().show();
                });
            }
        });
    };
})(jQuery);
$("#lgip").makePlacer("Enter Username Or Email");

JSFiddle:http://jsfiddle.net/QQdfQ/1/

相关文章: