首页 文章

输入Internet Explorer的占位符

提问于
浏览
170

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

可悲的是,包括IE 9在内的Internet Explorer不支持它 .

那里已经有一些占位符模拟器脚本了 . 它们通常通过将默认文本放入输入字段,给它一个灰色并在您聚焦输入字段后再次将其删除来工作 .

这种方法的缺点是占位符文本在输入字段中 . 从而:

  • 脚本无法轻松检查输入字段是否为空

  • 服务器端处理必须检查默认值,以便不将占位符插入数据库 .

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

17 回答

  • 6

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

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

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

  • 1

    您可以使用 :

    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);
    
  • 4

    很简单:

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

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

    JQuery目录:

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

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

  • 12

    在查看HTML5 Cross Browser Polyfills的"Web Forms : input placeholder"部分时,我看到的是jQuery-html5-placeholder .

    我用IE9尝试了demo,它看起来像是用一个span包装你的 <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,宣传自己为"No dependencies (so no need to include jQuery, unlike most placeholder polyfill scripts)."

    Edit: 对于那些对"what"感兴趣的人"what",How to create an advanced HTML5 placeholder polyfill,它会介绍创建一个执行此操作的jQuery插件的过程 .

    另外,请参阅keep placeholder on focus in IE10,了解占位符文本如何在IE10焦点上消失,这与Firefox和Chrome不同 . 不确定是否有解决此问题的方法 .

  • 149

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

  • 0

    使用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();
          });
      });
    }
    
  • 1

    在尝试了一些建议并在IE中查看问题后,这是有效的:

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

    我喜欢什么 - 你只需要包含js文件 . 无需启动它或任何东西 .

  • 0
    • 仅适用于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('');
            }
          });
        });
      }
    });
    
  • 38

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

    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 :)');
    
  • -1

    我想出了一个简单的占位符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');
                }
            });
        });
    });
    
  • 2

    Placeholdr是我写的超轻量级嵌入式占位符jQuery polyfill . 它不到1 KB缩小 .

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

    • Placeholdr扩展jQuery $.fn.val() function以防止因Placeholdr而在输入字段中出现文本时出现意外返回值 . 因此,如果您坚持使用jQuery API来访问您的字段' values, you won' t需要更改一个东西 .

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

    同样,我与Placeholdr的目标是为占位符问题提供一个简单的插入式解决方案 . 让我知道Github是否还有其他任何你对Placeholdr支持感兴趣的事情 .

  • 2

    插入插件并检查ie是完全workingjquery.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>
    
  • 0

    这是一个纯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>
    
  • 4

    注意:作者这个polyfill声称它_844131_但是根据IE11的评论不是这样,但IE11 has native support, as do most modern browsers

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

  • 2

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

    适用于ie7,ie8,ie9 .

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

  • -1

    我在创建自己的jQuery插件后感到沮丧,因为现有的填充程序会将占位符隐藏在焦点上,这会产生较差的用户体验,也与Firefox,Chrome和Safari处理它的方式不相符 . 如果您希望在首次加载页面或弹出窗口时聚焦输入,同时在输入文本之前仍显示占位符,则尤其如此 .

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

相关问题