2014-02-19 182 views
1

我有以下基于按钮单击运行的代码。在IE9中设置占位符att

function ClickYes() {  
     $('#<%=txtMsg.ClientID%>').attr('placeholder', 'Tell me more'); 
    } 

按钮被声明为以下

<button type="button" class="com-yes-btn2 feedback-btn-grey empx11b12" id="btnYes" onclick="javascript:ClickYes();"> 

</button> 

的问题是,我需要设置占位ATT动态基于事件,在Chrome和Firefox的行为是正确的,但使用IE9占位符时属性没有被添加。

我如何管理这种跨浏览器

感谢

+0

IE9不支持使用'placeholder'属性,但有解决方法。看看这个答案的类似问题:http:// stackoverflow。com/a/13281620/1423456 –

回答

3

占位符不被IE 9支撑。但是你可以环顾四周,如JavaScript一些替代实现这个很容易

<input type="text" placeholder="test" value="placeholder text" 
onfocus="if (this.value=='placeholder text') this.value = ''" onblur="if (this.value=='') this.value = 'placeholder text'"/> 

但是你需要照顾,而使用这种方法,因为这种方法设置textboxvalue。所以当你找回它时,你会得到它的价值。所以,无论何时使用它,您都需要检查占位符值。

你的功能会是这样

function ClickYes() {  
     // for modern browsers 
     $('#txtMsg').attr('placeholder', 'Tell me more'); 

     // for older browsers 
     $('#txtMsg').val('Tell me more'); 
     $('#txtMsg').css('color','#CCC'); 
    } 

现在你需要处理focusblur事件,使其完成这样

$(document).ready(function() { 
    $("#txtMsg").focus(function() { 
     if ($(this).val() == 'Tell me more') { 
      $(this).val(''); 
      $(this).css('color', 'black'); 
     } 
    }); 
    $("#txtMsg").blur(function() { 
     if (!$(this).val()) { 
      $(this).val('Tell me more'); 
      $('#txtMsg').css('color', '#CCC'); 
     } 
    }); 
}); 

Js Fiddle Demo

Js Fiddle Demo 2

3

IE9不支持placeholder属性,则需要使用blur & focus事件模拟这个功能。

function ClickYes() { 

    var element = $('#<%=txtMsg.ClientID%>'); 

    // default action (on moderns browsers) 
    var placeholder = function() { 
     element.attr('placeholder', 'Tell me more'); 
    }; 

    if (navigator.appVersion.match(/MSIE [\d.]+/)) { 
     // if MSIE: we override this function 
     placeholder = function() { 
      var placeholderText = 'Tell me more'; 
      element.val(placeholderText); 
      element.blur(function(){ 
       $(this).val() == '' ? $(this).val(placeholderText) : false; 
      }); 
      element.focus(function(){ 
       $(this).val() == placeholderText ? $(this).val('') : false; 
      }); 
     }; 
    }; 

    placeholder(); // we call the created function 
} 

来源:placeholder is not working in IE9

1

我用placeholder.js,这是很容易使用: PlaceHolder

只能通过refrenced到jQuery和placeholder.js和下面的代码

$('input, textarea').placeholder();