Lenny-Hu / note

blog
5 stars 1 forks source link

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

Open Lenny-Hu opened 5 years ago

Lenny-Hu commented 5 years ago
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>