Lenny-Hu/note

vue 的 placeholder 指令(为了兼容ie9)

Lenny-Hu opened this issue · 0 comments

  • 自动计算位置
  • 独立,无css依赖
  • 检测placeholder支持
  • 需要jquery
directives: {
        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();
            }
          }
        }
      }

使用

<div class="ipt-box">
      <input type="text" v-model.trim="form.text" v-placeholder placeholder="请输入内容">
    </div>
    <div class="ipt-box f-pr">
      <textarea v-placeholder v-model.trim="form.content" placeholder="请输入内容"></textarea>
    </div>