IE9及如下兼容placeholder

在input輸入框中使用placeholder,能夠給用戶起到提醒或指引的做用,可是IE9及如下的IE版本都不支持placeholder,故在此給出一些解決方法:css

  1. 使用value來代替(作非空判斷時須要排除值等於placeholder值的狀況)
  2. 添加標籤(需注意如何觸發事件)
  3. 引用現成插件 jquery.placeholder.min.js(請自行搜索下載,此處就很少說了)

無論用哪一種方法,咱們都要先判斷瀏覽器是否不支持placeholder,不支持的時候咱們才須要處理jquery

function placehSupport() {
   return 'placeholder' in document.createElement('input')  ;
}

1.瀏覽器

<body>
    <input id="title" type="text" placeholder="請輸入標題">
<script src="jquery-1.11.3.js"></script>
<script>
    $(function(){
        function placehSupport() {
            return 'placeholder' in document.createElement('input');
        }    
        if(!placehSupport){  // 判斷瀏覽器是否支持 placeholder
      var placeVal = $('input#title').attr('placeholder'); 
      $(
'input#title').val(placeVal);
      $(
'input#title').focus(function(){
        
if($.trim($('input#title').val())==placeVal ) {
          $(
'input#title').val('');
        }
      });
      input.blur(function(){
        
if($.trim($('input#title').val())=='') {
           $('input#title').val(placeVal );
         } }); } });
</script>
</body>
 

2.app

<body>
<div class="input-box">
    <input class="input1" type="text" placeholder="請輸入標題">
</div>
<div class="input-box">
    <input class="input2" type="text" placeholder="請輸入文章">
</div>
<script src="jquery-1.11.3.js"></script>
<script>
    function placeholderSupport() {
        return 'placeholder' in document.createElement('input');
    }
    if(!placeholderSupport()){   // 判斷瀏覽器是否支持 placeholder
        $("input[placeholder]").each(function(){
            var _this = $(this);
            var left = _this.css("padding-left");
            _this.parent().append('<span class="placeholder" data-type="placeholder" style="left: '+left+'">'+_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");
        });
    }
})
</script>
</body>
相關文章
相關標籤/搜索