IE浏览器 placeholder 兼容性

767 阅读1分钟

遇到在ie8浏览器下placeholder 不显示的情况,此时我们需要做兼容处理

html部分

<div class="form-div">
  <div>
    <div class="label">姓名:</div>
  </div>
  <div class="input-div">
    <input id="name" type="text" placeholder="请输入您的姓名" />
  </div>
</div>

css部分

.form-div {
    width: 260px;
    margin: 50px auto;
  }
  .input-div {
    width: 260px;
    height: 40px;
    position: relative;
  }
  .input-div input {
    width: 260px;
    height: 40px;
    line-height: 40px;
    border: 1px solid #e0e0e0;
    box-sizing: border-box;
    padding-left: 10px;
    padding-right: 10px;
    background-color: #fff;
  }

实现的效果(在谷歌上)

IE8显示效果(placeholder 里面的内容未显示)

解决办法:

利用jquery判断浏览器是否支持placeholder,如果不支持则给当前input框添加一个span标签,jquery代码如下:

(function changePlaceholder() {
    function placeholderSupport() {
      return "placeholder" in document.createElement("input");
    }
    if (!placeholderSupport()) {
      //判断浏览器是否支持 placeholder
      $("[placeholder]")
        .each(function() {
          var _this = $(this);
          var left = _this.css("padding-left");
          _this
            .parent()
            .append(
              '<span class="placeholder" data-type="placeholder">' +
                _this.attr("placeholder") +
                "</span>"
            );
          if (_this.val() != "") {//内容不为空时要隐藏
            _this
              .parent()
              .find("span.placeholder")
              .hide();
          } else {
            _this
              .parent()
              .find("span.placeholder")
              .show();
          }
        })
        .on("focus", function() {//鼠标点击输入框后隐藏
          $(this)
            .parent()
            .find("span.placeholder")
            .hide();
        })
        .on("blur", function() {//失去焦点显示
          var _this = $(this);
          if (_this.val() != "") {
            _this
              .parent()
              .find("span.placeholder")
              .hide();
          } else {
            _this
              .parent()
              .find("span.placeholder")
              .show();
          }
        });
      // 点击表示placeholder的标签相当于触发input
      $("span.placeholder").on("click", function() {
        $(this).hide();
        $(this)
          .siblings("[placeholder]")
          .trigger("click");
        $(this)
          .siblings("[placeholder]")
          .trigger("focus");
      });
    }
  })();

添加的css代码:

.placeholder {
    position: absolute;
    height: 40px;
    color: #c5c5c5;
    text-align: left;
    width: 260px;
    line-height: 40px;
    padding-left: 10px;
    left: 0;
  }

所以在ie8的检查元素就会显示如下