180

HTML5 では要素にplaceholder属性が導入されinput、グレーアウトされたデフォルト テキストを表示できます。

残念ながら、IE 9 を含む Internet Explorer ではサポートされていません。

いくつかのプレースホルダー シミュレーター スクリプトが既に存在します。それらは通常、デフォルトテキストを入力フィールドに入れ、灰色にして、入力フィールドにフォーカスするとすぐに再び削除することで機能します。

このアプローチの欠点は、プレースホルダー テキストが入力フィールドにあることです。したがって:

  1. スクリプトは、入力フィールドが空かどうかを簡単に確認できません
  2. プレースホルダーをデータベースに挿入しないように、サーバー側の処理でデフォルト値をチェックする必要があります。

プレースホルダー テキストが入力自体に含まれていない解決策が必要です。

4

17 に答える 17

154

HTML5 Cross Browser Polyfillsの「WebForms :input placeholder」セクションを見て、私が見たのはjQuery-html5-placeholderでした。

IE9でデモを試してみました<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>

他にもシムがありますが、全部は見ていません。それらの1つであるPlaceholders.jsは、「依存関係がない(したがって、ほとんどのプレースホルダーポリフィルスクリプトとは異なり、jQueryを含める必要がない)」とアドバタイズします。

編集:「どのように」「何を」に興味がある人のために、これを行うjQueryプラグインを作成するプロセスをウォークスルーする高度なHTML5プレースホルダーポリフィルを作成する方法。

また、FirefoxやChromeとは異なり、IE10でプレースホルダーテキストがフォーカスで消える方法についてのコメントについては、IE10でプレースホルダーにフォーカスを維持するを参照してください。この問題の解決策があるかどうかわからない。

于 2011-08-29T03:36:02.137 に答える
39

私の経験で最高のものはhttps://github.com/mathiasbynens/jquery-placeholder ( html5please.comで推奨) です。http://afarkas.github.com/webshim/demos/index.htmlにも、より広範なポリフィル ライブラリの中で優れたソリューションがあります。

于 2012-03-27T21:27:47.167 に答える
13

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

1 つの入力だけで使用するには

$('#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();
      });
  });
} 
于 2012-07-01T00:17:37.293 に答える
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('');
        }
      });
    });
  }
});
于 2012-01-18T06:24:57.460 に答える
4

簡単な関数をお勧めします:

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 :)');
于 2012-11-24T21:22:18.830 に答える
2

この方法を使用して、非常に簡単な解決策を見つけました。

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

これは jquery のハックであり、私のプロジェクトでは完璧に機能しました

于 2011-09-01T17:55:03.360 に答える
2

次のように簡単です:

$(function() {
    ...

    var element = $("#selecter")
    if(element.val() === element.attr("placeholder"){

        element.text("").select().blur();
    }

    ...
});
于 2017-01-05T16:35:50.440 に答える
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');
            }
        });
    });
});
于 2013-06-18T02:21:49.373 に答える
1

この問題を解決するためにjqueryプラグインを作成しました..無料です..

JQuery ディレクトリ:

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

サイト: www.kegles.com.br/jquery-placeholder/

于 2011-10-31T19:53:21.297 に答える
0

これは、IE 8 以下のプレースホルダーを作成する純粋な JavaScript 関数 (jquery は不要) であり、パスワードに対しても機能します。HTML5 プレースホルダー属性を読み取り、フォーム要素の背後にスパン要素を作成し、フォーム要素の背景を透明にします。

/* 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>

于 2015-11-19T07:23:26.373 に答える
0

プラグインを挿入して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>
于 2015-01-29T13:51:29.530 に答える
0

注: このポリフィルの作成者は、「想像できるほぼすべてのブラウザーで動作する」と主張していますが、IE11 には当てはまらないコメントによると、ほとんどの最新ブラウザーと同様に、IE11 にはネイティブ サポートがあります。

Placeholders.jsは私が見た中で最高のプレースホルダー ポリフィルであり、軽量で、JQuery に依存せず、他の古いブラウザー (IE だけでなく) をカバーし、hide-on-input および run-once プレースホルダーのオプションがあります。

于 2014-01-13T14:33:47.677 に答える