簡體   English   中英

擴展jQuery以使占位符與我創建的相同

[英]Extend jQuery to make placeholder like i have created

我在<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:text占位符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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM