programing tip

IE9의 자리 표시 자

itbloger 2020. 6. 21. 20:13
반응형

IE9의 자리 표시 자


잘 알려진 문제인 것 같지만 Google에서 찾은 모든 솔루션이 새로 다운로드 한 IE9에서 작동하지 않습니다.

태그 에서 Placeholder속성 을 사용하기 위해 가장 좋아하는 방법은 무엇입니까?inputtextarea

선택 사항 : 나는 그것에 많은 시간을 잃어 버렸고 required아직 부동산을 찾지 않았다. 이것에 대한 조언이 있습니까? 분명히 PHP에서 값을 확인할 수 있지만 사용자를 돕기 위해이 속성은 매우 편리합니다.


HTML5 자리 표시 자 jQuery를 플러그인
-에 의해 마티아스 Bynens (공동 작업자 HTML5 상용구jsPerf )

https://github.com/mathiasbynens/jquery-placeholder

데모 및 예

http://mathiasbynens.be/demo/placeholder

추신 :
나는이 플러그인을 여러 번 사용하고 치료를 작동합니다. 또한 양식을 제출할 때 자리 표시 자 텍스트를 값으로 제출 하지 않습니다 (다른 플러그인에서 찾은 실제 고통).


나는 이것이 당신이 찾고있는 것이라고 생각합니다 : jquery-html5-placeholder-fix

이 솔루션은 기능 탐지 ( modernizr 사용 )를 사용하여 자리 표시자가 지원되는지 확인합니다. 그렇지 않으면 (jQuery를 통해) 지원을 추가하십시오.


jquery 또는 modenizer를 사용하지 않고 수행하려면 아래 코드를 사용할 수 있습니다.

(function(){

     "use strict";

     //shim for String's trim function..
     function trim(string){
         return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
     }

     //returns whether the given element has the given class name..
     function hasClassName(element, className){ 
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return false;
         var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
         return regex.test(element.className);
     }

     function removeClassName(element, className){
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return;
         element.className = elClassName.replace(
             new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
     }

     function addClassName(element, className){
         var elClassName = element.className;
         if(elClassName)
             element.className += " " + className;
         else
             element.className = className;
     }

     //strings to make event attachment x-browser.. 
     var addEvent = document.addEventListener ?
            'addEventListener' : 'attachEvent';
     var eventPrefix = document.addEventListener ? '' : 'on';

     //the class which is added when the placeholder is being used..
     var placeHolderClassName = 'usingPlaceHolder';

     //allows the given textField to use it's placeholder attribute
     //as if it's functionality is supported natively..
     window.placeHolder = function(textField){

         //don't do anything if you get it for free..
         if('placeholder' in document.createElement('input'))
             return;

         //don't do anything if the place holder attribute is not
         //defined or is blank..
         var placeHolder = textField.getAttribute('placeholder');        
         if(!placeHolder)
             return;

         //if it's just the empty string do nothing..
         placeHolder = trim(placeHolder);
         if(placeHolder === '')
             return;

         //called on blur - sets the value to the place holder if it's empty..
         var onBlur = function(){
             if(textField.value !== '') //a space is a valid input..
                 return;
             textField.value = placeHolder;
             addClassName(textField, placeHolderClassName);
         };

         //the blur event..
         textField[addEvent](eventPrefix + 'blur', onBlur, false);

         //the focus event - removes the place holder if required..
         textField[addEvent](eventPrefix + 'focus', function(){
             if(hasClassName(textField, placeHolderClassName)){
                removeClassName(textField, placeHolderClassName);
                textField.value = "";
             }
         }, false);

         //the submit event on the form to which it's associated - if the
         //placeholder is attached set the value to be empty..
         var form = textField.form;
         if(form){
             form[addEvent](eventPrefix + 'submit', function(){
                 if(hasClassName(textField, placeHolderClassName))
                     textField.value = '';
            }, false);
         }

         onBlur(); //call the onBlur to set it initially..
    };

}());

사용하려는 각 텍스트 필드에 placeHolder(HTMLInputElement)대해을 실행해야 하지만 그에 맞게 변경할 수 있다고 생각합니다! 또한로드가 아닌이 방법으로 페이지를로드 할 때 DOM에없는 입력에 대해 작동하도록 할 수 있습니다.

이것은 class : usingPlaceHolder를 입력 요소 에 적용하여 작동 하므로 스타일을 지정하는 데 사용할 수 있습니다 (예 : 규칙 .usingPlaceHolder { color: #999; font-style: italic; }추가하여 더보기 좋게 표시).


훨씬 더 나은 해결책이 있습니다. http://bavotasan.com/2011/html5-placeholder-jquery-fix/ IE10에서 브라우저에서만 작동하도록 약간 채택했습니다.

<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie10 lt-ie9" lang="en"> <![endif]-->
<!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->

    <script>
    // Placeholder fix for IE
      $('.lt-ie10 [placeholder]').focus(function() {
        var i = $(this);
        if(i.val() == i.attr('placeholder')) {
          i.val('').removeClass('placeholder');
          if(i.hasClass('password')) {
            i.removeClass('password');
            this.type='password';
          }     
        }
      }).blur(function() {
        var i = $(this);  
        if(i.val() == '' || i.val() == i.attr('placeholder')) {
          if(this.type=='password') {
            i.addClass('password');
            this.type='text';
          }
          i.addClass('placeholder').val(i.attr('placeholder'));
        }
      }).blur().parents('form').submit(function() {
        //if($(this).validationEngine('validate')) { // If using validationEngine
          $(this).find('[placeholder]').each(function() {
            var i = $(this);
            if(i.val() == i.attr('placeholder'))
              i.val('');
              i.removeClass('placeholder');

          })
        //}
      });
    </script>
    ...
    </html>

설명을 입력하려면 이것을 사용할 수 있습니다. 이것은 IE 9 및 다른 모든 브라우저에서 작동합니다.

<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>

자리 표시자를 지원하지 않는 브라우저를 감지하기 위해 mordernizr사용 하여이 간단한 코드를 작성하여 수정했습니다.

//If placeholder is not supported
if (!Modernizr.input.placeholder){ 

    //Loops on inputs and place the placeholder attribute
    //in the textbox.
    $("input[type=text]").each( function() { 
       $(this).val($(this).attr('placeholder')); 
    })
}

나는 늦었다는 것을 알고 있지만 머리에 태그를 삽입하는 해결책을 찾았습니다.

<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->


IE-9에서 작동하게하려면 아래에서 사용하십시오.

JQuery에는 다음이 포함되어야합니다.

jQuery(function() {
   jQuery.support.placeholder = false;
   webkit_type = document.createElement('input');
   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
   $(function() {

     if(!$.support.placeholder) {

       var active = document.activeElement;

       $(':text, textarea, :password').focus(function () {

       if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&         ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
          $(this).val('').removeClass('hasPlaceholder');
        }
      }).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&  ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() ==   $(this).attr('placeholder'))) {
     $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});

$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
     $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});

CSS 스타일에는 다음이 포함되어야합니다.

.hasPlaceholder {color: #aaa;}

A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:

// Placeholder fallback
if(!Modernizr.input.placeholder){

    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

}

I usually think fairly highly of http://cdnjs.com/ and they are listing:

//cdnjs.cloudflare.com/ajax/libs/placeholder-shiv/0.2/placeholder-shiv.js

Not sure who's code that is but it looks straightforward:

document.observe('dom:loaded', function(){
  var _test = document.createElement('input');
  if( ! ('placeholder' in _test) ){
    //we are in the presence of a less-capable browser
    $$('*[placeholder]').each(function(elm){
      if($F(elm) == ''){
        var originalColor = elm.getStyle('color');
        var hint = elm.readAttribute('placeholder');
        elm.setStyle('color:gray').setValue(hint);
        elm.observe('focus',function(evt){
          if($F(this) == hint){
            this.clear().setStyle({color: originalColor});
          }
        });
        elm.observe('blur', function(evt){
          if($F(this) == ''){
            this.setValue(hint).setStyle('color:gray');
          }
        });
      }
    }).first().up('form').observe('submit', function(evt){
      evt.stop();
      this.select('*[placeholder]').each(function(elm){
        if($F(elm) == elm.readAttribute('placeholder')) elm.clear();
      });
      this.submit();
    });
  }
});

I searched on the internet and found a simple jquery code to handle this problem. In my side, it was solved and worked on ie 9.

$("input[placeholder]").each(function () {
        var $this = $(this);
        if($this.val() == ""){
            $this.val($this.attr("placeholder")).focus(function(){
                if($this.val() == $this.attr("placeholder")) {
                    $this.val("");
                }
            }).blur(function(){
                if($this.val() == "") {
                    $this.val($this.attr("placeholder"));
                }
            });
        }
    });

참고URL : https://stackoverflow.com/questions/6366021/placeholder-in-ie9

반응형