/** jquery enplaceholder plug enplaceholder是一个跨浏览器实现placeholder效果的jquery插件 version 1.0 by frans.lee */ (function ($) { $.fn.extend({ "placeholder":function (options) { options = $.extend({ placeholdercolor:'#aca899', isusespan:false, //是否使用插入span标签模拟placeholder的方式,默认false,默认使用value模拟 oninput:true //使用标签模拟(isusespan为true)时,是否绑定oninput事件取代focus/blur事件 }, options); $(this).each(function () { var _this = this; var supportplaceholder = 'placeholder' in document.createelement('input'); if (!supportplaceholder) { var defaultvalue = $(_this).attr('placeholder'); var defaultcolor = $(_this).css('color'); if (options.isusespan == false) { $(_this).focus(function () { var pattern = new regexp("^" + defaultvalue + "$|^$"); pattern.test($(_this).val()) && $(_this).val('').css('color', defaultcolor); }).blur(function () { if ($(_this).val() == defaultvalue) { $(_this).css('color', defaultcolor); } else if ($(_this).val().length == 0) { $(_this).val(defaultvalue).css('color', options.placeholdercolor) } }).trigger('blur'); } else { var $imitate = $('' + defaultvalue + ''); $imitate.css({ 'margin-left':$(_this).css('margin-left'), 'margin-top':$(_this).css('margin-top'), 'font-size':$(_this).css('font-size'), 'font-family':$(_this).css('font-family'), 'font-weight':$(_this).css('font-weight'), 'padding-left':parseint($(_this).css('padding-left')) + 2 + 'px', 'line-height':_this.nodename.tolowercase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerheight() + 'px', 'padding-top':_this.nodename.tolowercase() == 'textarea' ? parseint($(_this).css('padding-top')) + 2 : 0 }); $(_this).before($imitate.click(function () { $(_this).trigger('focus'); })); $(_this).val().length != 0 && $imitate.hide(); if (options.oninput) { //绑定oninput/onpropertychange事件 var inputchangeevent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange'; $(_this).bind(inputchangeevent, function () { $imitate[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block'; }); } else { $(_this).focus(function () { $imitate.hide(); }).blur(function () { /^$/.test($(_this).val()) && $imitate.show(); }); } } } }); return this; } }); })(jquery);