placeholder.js 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ;(function ($) {
  2. $.fn.extend({
  3. "placeholder":function (options) {
  4. options = $.extend({
  5. placeholderColor:'#ACA899',
  6. isUseSpan:false, //是否使用插入span标签模拟placeholder的方式,默认false,默认使用value模拟
  7. onInput:true //使用标签模拟(isUseSpan为true)时,是否绑定onInput事件取代focus/blur事件
  8. }, options);
  9. $(this).each(function () {
  10. var _this = this;
  11. var supportPlaceholder = 'placeholder' in document.createElement('input');
  12. if (!supportPlaceholder) {
  13. var defaultValue = $(_this).attr('placeholder');
  14. var defaultColor = $(_this).css('color');
  15. if (options.isUseSpan == false) {
  16. $(_this).focus(function () {
  17. var pattern = new RegExp("^" + defaultValue + "$|^$");
  18. pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
  19. }).blur(function () {
  20. if ($(_this).val() == defaultValue) {
  21. $(_this).css('color', defaultColor);
  22. } else if ($(_this).val().length == 0) {
  23. $(_this).val(defaultValue).css('color', options.placeholderColor)
  24. }
  25. }).trigger('blur');
  26. } else {
  27. var $imitate = $('<span class="wrap-placeholder" style="position:absolute; display:inline-block; overflow:hidden; color:'+options.placeholderColor+'; width:'+$(_this).outerWidth()+'px; height:'+$(_this).outerHeight()+'px;">' + defaultValue + '</span>');
  28. $imitate.css({
  29. 'margin-left':$(_this).css('margin-left'),
  30. 'margin-top':$(_this).css('margin-top'),
  31. 'font-size':$(_this).css('font-size'),
  32. 'font-family':$(_this).css('font-family'),
  33. 'font-weight':$(_this).css('font-weight'),
  34. 'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px',
  35. 'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px',
  36. 'padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0
  37. });
  38. $(_this).before($imitate.click(function () {
  39. $(_this).trigger('focus');
  40. }));
  41. $(_this).val().length != 0 && $imitate.hide();
  42. if (options.onInput) {
  43. //绑定oninput/onpropertychange事件
  44. var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
  45. $(_this).bind(inputChangeEvent, function () {
  46. $imitate[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
  47. });
  48. } else {
  49. $(_this).focus(function () {
  50. $imitate.hide();
  51. }).blur(function () {
  52. /^$/.test($(_this).val()) && $imitate.show();
  53. });
  54. }
  55. }
  56. }
  57. });
  58. return this;
  59. }
  60. });
  61. })(jQuery);