js模拟placeholder效果1

由于有的浏览器不支持placeholder,所以写了一个jquery插件来模拟placeholder效果。

使用方法:$("#IDName").placeholder();

话不多说,直接上代码~~~

(function ($) {
    $.fn.placeholder = function (options) {
        var defaults = {
            pColor: "#BEBEBE",
            pActive: "#999",
            pFont: "14px",
            activeBorder: "#080",
            posL: 8,
            zIndex: "99"
        },
        opts = $.extend(defaults, options);
        $(".test").remove();
        return this.each(function () {
            if ("placeholder" in document.createElement("input")) return;
            $(this).parent().css("position", "relative");
//            var isIE = $.browser.msie,
//            version = $.browser.version;
            if(!$(this).is(":hidden")){//不支持placeholder的浏览器
                var $this = $(this),
                    msg = $this.attr("placeholder"),
                    iH = $this.outerHeight(),
                    iW = $this.outerWidth(),
                    iX = $this.position().left,
                    iY = $this.position().top,
                    oInput = $("<label>", {
                    "class": "test",
                    "text": msg,
                    "css": {
                        "position": "absolute",
                        "left": iX + "px",
                        "top": iY + "px",
                        "width": iW - opts.posL + "px",
                        "padding-left": opts.posL + "px",
                        "height": iH + "px",
                        "line-height": iH + "px",
                        "color": opts.pColor,
                        "font-size": opts.pFont,
                        "z-index": opts.zIndex,
                        "cursor": "text"
                    }
                    }).insertBefore($this);
                //初始状态就有内容
                var value = $this.val();
                if (value.length > 0) {
                	oInput.hide();
                };
                $this.on("focus", function () {
                    oInput.hide();
                    oInput.css("color", opts.pActive);
                }).on("blur", function () {
                    var value = $(this).val();
                    if (value.length == 0) {
                        oInput.css("color", opts.pColor).show();
                    }
                });
                oInput.on("click", function () {
                    $this.trigger("focus");
                    $(this).css("color", opts.pActive);
                });
                $this.filter(":focus").trigger("focus");
            }
        });
    };
})(jQuery);


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。