5 11 月, 2014

IE下实现placeholder效果的jquery插件

发现ie11都不支持placeholder,这是相当悲剧的。下面贴出一段简单的解决方法:

$(document).ready(
  function () {
    var doc = document,
      inputs = doc
        .getElementsByTagName('input'),
      supportPlaceholder = 'placeholder' in doc
        .createElement('input'),
      placeholder = function (
        input) {
        var text = input.getAttribute('placeholder'),
          defaultValue = input.defaultValue;
        if (defaultValue == '') {
          input.value = text
          input.setAttribute("old_color", input.style.color);
          input.style.color = "#c0c0c0";
        }
        input.onfocus = function () {
          this.style.color = this.getAttribute("old_color");
          if (input.value === text) {
            this.value = ''
          }
        };
        input.onblur = function () {
          if (input.value === '') {
            this.style.color = "#c0c0c0";
            this.value = text
          }
        }
      };
    if (!supportPlaceholder) {
      for (var i = 0, len = inputs.length; i < len; i++) {
        var input = inputs[i],
          text = input
            .getAttribute('placeholder');
        if (input.type === 'text' && text) {
          placeholder(input)
        }
      }
    }
  }
);

直接引用这段js就可以了。

原理

就是通过js获取表单的title,然后把title写入到表单中,当表单激活的时候,再清空表单内容就可以了。