Home  >  Q&A  >  body text

javascript - placeholder怎么做兼容?

placeholder在ie8就没用了,怎么做兼容啊?

PHP中文网PHP中文网2748 days ago418

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-10 16:19:51

    只能用JS做兼容。
    参考:http://www.cnblogs.com/jifeng/p/3983368.html

    reply
    0
  • 黄舟

    黄舟2017-04-10 16:19:51

    之前有处理过IE的textarea的占位符问题(虽然IE>8支持,但IE9,IE10对textarea初始时的value会取placeholder值)。
    虽然没有完全模拟原生的placeholder,但这样的(降级)处理也能接受。

    Talk is cheap, show you my code,js源码片段(这里已稍作变动)如下:

         
      if("ActiveXObject" in window){ // just for all IE
          var $textarea = $popupHTML.find('textarea');
          var textHolder = $textarea.attr('placeholder') 
                          || "我们非常重视您的建议,请在这里填写告诉我们";
    
          $textarea.parent(".textarea-wrap").length === 0 &&
              $textarea.removeAttr("placeholder").val('').wrap('<p class="textarea-wrap"></p>')
                  .after('<span class="j_holder">' + textHolder + '</span>');
            
            $popupHTML.on("click",".j_holder",function(){ $(this).siblings("textarea").focus(); })
            .find('textarea').on({
                focus: function(){
                    var $placehoder = $(this).siblings(".j_holder");
                    $.trim($(this).val()).length ? 
                        $placehoder.css('z-index','-1') : $placehoder.css('z-index','1');
                },
                keyup: function(){ $(this).trigger("focus"); },
                blur: function(){
                    var $placehoder = $(this).siblings(".j_holder");
                    var realVal = $.trim($(this).val());
                    $(this).val(realVal);
                    realVal.length ? 
                        $placehoder.css('z-index','-1') : $placehoder.css('z-index','1');
                }
            });
    
    }
    
    

    关于css定位,在此忽略~

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 16:19:51

    在输入框上再覆盖一层标签来模拟相同的效果吧。

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 16:19:51

    基本思路就是通过js来实现

    • 先定义输入框的字体为灰色样式,并设施提示文字。

    • 然后当keydown或者mousedown的时候改回样式清除内容。

    当然,比较好的方法是如果失去焦点的时候,看看是否有内容,没有内容继续上面的步骤,设置灰色和placeholder文字提示。

    reply
    0
  • Cancelreply