Lenny-Hu / note

blog
5 stars 1 forks source link

vue自定义常用指令 #89

Open Lenny-Hu opened 4 years ago

Lenny-Hu commented 4 years ago

表单输入框提示

// 表单元素的placeholder属性,用来兼容ie9
Vue.directive('placeholder', {
  inserted: function (el, binding, vnode) {
    if ('placeholder' in document.createElement('input')) {
      return false;
    }

    $el = $(el);
    $el.parent().css({
      position: 'relative'
    });

    var styleProperty = $el.css(['width', 'marginTop', 'marginLeft', 'paddingTop', 'paddingLeft', 'height', 'fontSize', 'border', 'lineHeight']);
    var position = $el.position();

    var $p = $('<span class="placeholder">' + $el.attr('placeholder') + '</span>');
    $p.css($.extend(styleProperty, position, {
      position: 'absolute',
      zIndex: 10,
      overflow: 'hidden',
      borderColor: 'transparent',
      color: '#888',
      whiteSpace: 'nowrap',
      display: 'block'
    }));
    $el.after($p);

    $el.on('focus', function () {
      $(this).next('.placeholder').hide();
    });

    $p.on('click', function () {
      $(this).hide();
      $(el).focus();
    });
  },
  update: function (el) {
    if ('placeholder' in document.createElement('input')) {
      return false;
    }

    var $p = $(el).next('.placeholder');
    if (el.value) {
      $p.hide();
    } else {
      $p.show();
    }
  }
});