【问题标题】:Input placeholders for Internet ExplorerInternet Explorer 的输入占位符
【发布时间】:2011-07-28 04:30:44
【问题描述】:

HTML5 在input 元素上引入了placeholder 属性,它允许显示灰色的默认文本。

遗憾的是 Internet Explorer,包括 IE 9 不支持它。

那里已经有一些占位符模拟器脚本。它们通常通过将默认文本放入输入字段,将其设置为灰色并在您关注输入字段后再次将其删除。

这种方法的缺点是占位符文本位于输入字段中。因此:

  1. 脚本无法轻松检查输入字段是否为空
  2. 服务器端处理必须检查默认值,以免将占位符插入数据库。

我想要一个解决方案,占位符文本不在输入本身中。

【问题讨论】:

    标签: javascript html internet-explorer placeholder


    【解决方案1】:

    在查看HTML5 Cross Browser Polyfills 的“Web 表单:输入占位符”部分时,我看到的是jQuery-html5-placeholder

    我用 IE9 尝试了demo,它看起来像是用跨度包裹了你的<input>,并用占位符文本覆盖了一个标签。

    <label>Text:
      <span style="position: relative;">
        <input id="placeholder1314588474481" name="text" maxLength="6" type="text" placeholder="Hi Mom">
        <label style="font: 0.75em/normal sans-serif; left: 5px; top: 3px; width: 147px; height: 15px; color: rgb(186, 186, 186); position: absolute; overflow-x: hidden; font-size-adjust: none; font-stretch: normal;" for="placeholder1314588474481">Hi Mom</label>
      </span>
    </label>
    

    那里还有其他垫片,但我没有全部看。其中之一,Placeholders.js,将自己宣传为“没有依赖项(因此不需要包含 jQuery,不像大多数占位符 polyfill 脚本)。”

    编辑:对于那些对“如何”和“什么”更感兴趣的人,How to create an advanced HTML5 placeholder polyfill 将介绍创建执行此操作的 jQuery 插件的过程。

    另外,请参阅 keep placeholder on focus in IE10 了解 cmets 的占位符文本如何在 IE10 的焦点上消失,这与 Firefox 和 Chrome 不同。不知道有没有办法解决这个问题。

    【讨论】:

    • 在 IE7、IE8 和 IE9 中运行良好。
    • 该插件不再维护,并且有很多已知问题。
    • 投反对票?答案包含指向其他垫片的链接。更新为包含一个非 jQuery 的。
    • 插件的github页面不存在了。 Here is another one.
    • 不是太大的粉丝会导致输入被修改,我建议在下面查看尼克的答案。它使用透明覆盖而不是修改输入的值
    【解决方案2】:

    我找到了一个使用这种方法的非常简单的解决方案:

    http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

    这是一个 jquery hack,它在我的项目中完美运行

    【讨论】:

    • 这个覆盖所有的,因此它适用于所有浏览器,无论 IE、WebKit 或 Opera 是什么
    【解决方案3】:

    我写了一个jquery插件来解决这个问题..它是免费的..

    JQuery 目录:

    http://plugins.jquery.com/project/kegles-jquery-placeholder

    网站: www.kegles.com.br/jquery-placeholder/

    【讨论】:

    • 似乎工作得很好,而且非常简单......为什么只有两个赞成票?
    【解决方案4】:
    • 仅适用于 IE9+

    以下解决方案使用占位符属性绑定到输入文本元素。它仅模拟 IE 的占位符行为,如果未更改,则在提交时清除输入的值字段。

    添加此脚本,IE 似乎支持 HTML5 占位符。

      $(function() {
      //Run this script only for IE
      if (navigator.appName === "Microsoft Internet Explorer") {
        $("input[type=text]").each(function() {
          var p;
         // Run this script only for input field with placeholder attribute
          if (p = $(this).attr('placeholder')) {
          // Input field's value attribute gets the placeholder value.
            $(this).val(p);
            $(this).css('color', 'gray');
            // On selecting the field, if value is the same as placeholder, it should become blank
            $(this).focus(function() {
              if (p === $(this).val()) {
                return $(this).val('');
              }
            });
             // On exiting field, if value is blank, it should be assigned the value of placeholder
            $(this).blur(function() {
              if ($(this).val() === '') {
                return $(this).val(p);
              }
            });
          }
        });
        $("input[type=password]").each(function() {
          var e_id, p;
          if (p = $(this).attr('placeholder')) {
            e_id = $(this).attr('id');
            // change input type so that the text is displayed
            document.getElementById(e_id).type = 'text';
            $(this).val(p);
            $(this).focus(function() {
              // change input type so that password is not displayed
              document.getElementById(e_id).type = 'password';
              if (p === $(this).val()) {
                return $(this).val('');
              }
            });
            $(this).blur(function() {
              if ($(this).val() === '') {
                document.getElementById(e_id).type = 'text';
                $(this).val(p);
              }
            });
          }
        });
        $('form').submit(function() {
          //Interrupt submission to blank out input fields with placeholder values
          $("input[type=text]").each(function() {
            if ($(this).val() === $(this).attr('placeholder')) {
              $(this).val('');
            }
          });
         $("input[type=password]").each(function() {
            if ($(this).val() === $(this).attr('placeholder')) {
               $(this).val('');
            }
          });
        });
      }
    });
    

    【讨论】:

    • 很多用户还在用IE8,有些甚至用IE7。因此,如果它不支持它们,我就不会这样做
    【解决方案5】:

    根据我的经验,最好的一个是https://github.com/mathiasbynens/jquery-placeholder(由html5please.com 推荐)。 http://afarkas.github.com/webshim/demos/index.html 在其更广泛的 polyfill 库中也有一个很好的解决方案。

    【讨论】:

    • +1 在 jQuery-html5-placeholder 上。这看起来好多了,并且处理了一些被另一个忽略的边缘情况(例如隐藏字段)
    • 不得不说这次 StackOverflow 提供了一个糟糕的建议。在 IE 中单击时,jQuery 占位符不会清除输入。
    【解决方案6】:

    使用 jQuery 实现,您可以在提交时轻松删除默认值。下面是一个例子:

    $('#submit').click(function(){
       var text = this.attr('placeholder');
       var inputvalue = this.val();  // you need to collect this anyways
       if (text === inputvalue) inputvalue = "";
    
       // $.ajax(...  // do your ajax thing here
    
    });
    

    我知道您正在寻找覆盖,但您可能更喜欢这条路线的轻松(现在知道我在上面写的内容)。如果是这样,那么我为我自己的项目编写了这个,它工作得非常好(需要 jQuery),并且只需要几分钟就可以为你的整个站点实现。它首先提供灰色文本,焦点时为浅灰色,打字时为黑色。只要输入字段为空,它还会提供占位符文本。

    首先设置您的表单并在输入标签中包含您的占位符属性。

    <input placeholder="enter your email here">
    

    只需复制此代码并将其保存为 placeholder.js。

    (function( $ ){
    
       $.fn.placeHolder = function() {  
          var input = this;
          var text = input.attr('placeholder');  // make sure you have your placeholder attributes completed for each input field
          if (text) input.val(text).css({ color:'grey' });
          input.focus(function(){  
             if (input.val() === text) input.css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){     
                input.val("").css({ color:'black' });  
             });
          });
          input.blur(function(){ 
             if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' }); 
          }); 
          input.keyup(function(){ 
            if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
                input.val("").css({ color:'black' });
            });               
          });
          input.mouseup(function(){
            if (input.val() === text) input.selectRange(0,0); 
          });   
       };
    
       $.fn.selectRange = function(start, end) {
          return this.each(function() {
            if (this.setSelectionRange) { this.setSelectionRange(start, end);
            } else if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true); 
                range.moveEnd('character', end); 
                range.moveStart('character', start); 
                range.select(); 
            }
          });
       };
    
    })( jQuery );
    

    仅用于一个输入

    $('#myinput').placeHolder();  // just one
    

    当浏览器不支持 HTML5 占位符属性时,我建议您在网站上的所有输入字段上实现它:

    var placeholder = 'placeholder' in document.createElement('input');  
    if (!placeholder) {      
      $.getScript("../js/placeholder.js", function() {   
          $(":input").each(function(){   // this will work for all input fields
            $(this).placeHolder();
          });
      });
    } 
    

    【讨论】:

    • 您能否为上述内容创建一个小提琴/演示,也将对我和未来的观众有所帮助。
    • 是否支持密码字段。
    【解决方案7】:

    我建议你一个简单的功能:

    function bindInOut(element,value)
    {
        element.focus(function()
        {
            if(element.val() == value) element.val('');         
        }).
        blur(function()
        {
            if(element.val() == '') element.val(value);
        });
    
        element.blur();
    }
    

    要使用它,请以这种方式调用它:

    bindInOut($('#input'),'Here your value :)');
    

    【讨论】:

      【解决方案8】:

      在尝试了一些建议并在 IE 中看到问题后,这是一个可行的方法:

      https://github.com/parndt/jquery-html5-placeholder-shim/

      我喜欢的 - 你只需包含 js 文件。无需启动它或任何东西。

      【讨论】:

      • 使用此占位符后在 ie 中工作正常,但如果表单中有任何错误,在显示表单错误时占位符文本与输入字段未对齐,我试图解决但无法做到.你能指导我如何解决。
      • 我真的比价值修改版本更喜欢这个。我希望占位符的 html5 版本也能以这种方式工作! (即在输入一些文本之前保留占位符,而不是失去焦点上的值)
      【解决方案9】:

      我想出了一个简单的占位符 JQuery 脚本,它允许自定义颜色,并在聚焦时使用不同的清除输入行为。它取代了 Firefox 和 Chrome 中的默认占位符,并增加了对 IE8 的支持。

      // placeholder script IE8, Chrome, Firefox
      // usage: <input type="text" placeholder="some str" />
      $(function () { 
          var textColor = '#777777'; //custom color
      
          $('[placeholder]').each(function() {
              (this).attr('tooltip', $(this).attr('placeholder')); //buffer
      
              if ($(this).val() === '' || $(this).val() === $(this).attr('placeholder')) {
                  $(this).css('color', textColor).css('font-style','italic');
                  $(this).val($(this).attr('placeholder')); //IE8 compatibility
              }
      
              $(this).attr('placeholder',''); //disable default behavior
      
              $(this).on('focus', function() {
                  if ($(this).val() === $(this).attr('tooltip')) {
                      $(this).val('');
                  }
              });
      
              $(this).on('keydown', function() {
                  $(this).css('font-style','normal').css('color','#000');
              });
      
              $(this).on('blur', function() {
                  if ($(this).val()  === '') {
                      $(this).val($(this).attr('tooltip')).css('color', textColor).css('font-style','italic');
                  }
              });
          });
      });
      

      【讨论】:

      • 完美的问候,但是你有一个错误 (this).attr('tooltip', $(this).attr('placeholder')); //缓冲区将此行更改为 $(this).attr('tooltip', $(this).attr('placeholder')); //缓冲区
      【解决方案10】:

      Placeholdr 是我编写的一个超轻量级的插入式占位符 jQuery polyfill。压缩后不到 1 KB。

      我确保这个库解决了您的两个问题:

      1. Placeholdr 扩展了 jQuery $.fn.val() function 以防止在输入字段中出现文本时出现意外返回值作为占位符的结果。因此,如果您坚持使用 jQuery API 来访问字段值,则无需更改任何内容。

      2. Placeholdr 监听表单提交,并从字段中删除占位符文本,以便服务器只看到一个空值。

      同样,我使用 Placeholderr 的目标是为占位符问题提供一个简单的直接解决方案。如果您对 Placeholderr 支持感兴趣,请在 Github 上告诉我。

      【讨论】:

        【解决方案11】:

        你可以使用:

        var placeholder = 'search  here';
        
        $('#search').focus(function(){
            if ($.trim($(this).val()) ===  placeholder){
                this.value ='';
            }
        }).blur(function(){
            if ($.trim($(this).val()) ===  ''){
                this.value = placeholder;
            }
        }).val(placeholder);
        

        【讨论】:

          【解决方案12】:

          我使用jquery.placeholderlabels。它基于this,可以演示here

          适用于 ie7、ie8、ie9。

          行为模仿当前的 firefox 和 chrome 行为 - “占位符”文本在焦点上保持可见,并且只有在字段中键入内容后才会消失。

          【讨论】:

            【解决方案13】:

            在对现有的垫片将占位符隐藏在焦点上感到沮丧之后,我创建了自己的 jQuery 插件,这会造成较差的用户体验,并且与 Firefox、Chrome 和 Safari 处理它的方式不匹配。如果您希望在第一次加载页面或弹出窗口时聚焦输入,同时在输入文本之前仍显示占位符,则尤其如此。

            https://github.com/nspady/jquery-placeholder-labels/

            【讨论】:

              【解决方案14】:

              注意:这个 polyfill 的作者声称它“几乎可以在任何你能想象到的浏览器中工作”,但根据 cmets 的说法,这对于 IE11 并不适用,但是 IE11 has native support, as do most modern browsers

              Placeholders.js 是我见过的最好的占位符 polyfill,轻量级,不依赖于 JQuery,涵盖其他较旧的浏览器(不仅仅是 IE),并且具有输入时隐藏和运行一次占位符选项.

              【讨论】:

              • @Niclas IE9 及更高版本对占位符有自己的原生支持。
              • 我已在此答案中添加了一条注释,其中包含用于占位符的 caniuse 链接。
              【解决方案15】:

              插入插件并检查 ie 是否完美运行jquery.placeholder.js

                  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
                  <script src="jquery.placeholder.js"></script>
                  <script>
                      // To test the @id toggling on password inputs in browsers that don’t support changing an input’s @type dynamically (e.g. Firefox 3.6 or IE), uncomment this:
                      // $.fn.hide = function() { return this; }
                      // Then uncomment the last rule in the <style> element (in the <head>).
                      $(function() {
                          // Invoke the plugin
                          $('input, textarea').placeholder({customClass:'my-placeholder'});
                          // That’s it, really.
                          // Now display a message if the browser supports placeholder natively
                          var html;
                          if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
                              html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin won’t run in this case, since it’s not needed. If you want to test the plugin, use an older browser ;)';
                          } else if ($.fn.placeholder.input) {
                              html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
                          }
                          if (html) {
                              $('<p class="note">' + html + '</p>').insertAfter('form');
                          }
                      });
                  </script>
              

              【讨论】:

                【解决方案16】:

                这是一个纯 javascript 函数(不需要 jquery),它将为 IE 8 及更低版本创建占位符,它也适用于密码。它读取 HTML5 占位符属性并在表单元素后面创建一个 span 元素并使表单元素背景透明:

                /* Function to add placeholders to form elements on IE 8 and below */
                function add_placeholders(fm) {	
                	for (var e = 0; e < document.fm.elements.length; e++) {
                		if (fm.elements[e].placeholder != undefined &&
                		document.createElement("input").placeholder == undefined) { // IE 8 and below					
                			fm.elements[e].style.background = "transparent";
                			var el = document.createElement("span");
                			el.innerHTML = fm.elements[e].placeholder;
                			el.style.position = "absolute";
                			el.style.padding = "2px;";
                			el.style.zIndex = "-1";
                			el.style.color = "#999999";
                			fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
                			fm.elements[e].onfocus = function() {
                					this.style.background = "yellow";	
                			}
                			fm.elements[e].onblur = function() {
                				if (this.value == "") this.style.background = "transparent";
                				else this.style.background = "white";	
                			}		
                		} 
                	}
                }
                
                add_placeholders(document.getElementById('fm'))
                <form id="fm">
                  <input type="text" name="email" placeholder="Email">
                  <input type="password" name="password" placeholder="Password">
                  <textarea name="description" placeholder="Description"></textarea>
                </form>

                【讨论】:

                  【解决方案17】:

                  像这样简单:

                  $(function() {
                      ...
                  
                      var element = $("#selecter")
                      if(element.val() === element.attr("placeholder"){
                  
                          element.text("").select().blur();
                      }
                  
                      ...
                  });
                  

                  【讨论】:

                    猜你喜欢
                    • 2014-02-19
                    • 2012-01-27
                    • 2014-11-24
                    • 2017-07-23
                    • 2013-07-20
                    • 2013-11-12
                    • 1970-01-01
                    • 2015-11-19
                    相关资源
                    最近更新 更多