我有以下基于按钮单击运行的代码。
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>问题是,我需要根据事件动态设置占位符,在chrome和firefox中,行为是正确的,但是在使用IE9占位符属性时没有添加。
如何管理这个跨浏览器?
谢谢
发布于 2014-02-19 13:30:05
是的,IE9不支持占位符。
<input type="text" placeholder="test" value="placeholder text"
onfocus="if (this.value=='placeholder text') this.value = ''" onblur="if (this.value=='') this.value = 'placeholder text'"/>但是,在使用这种方法设置value of textbox时,您需要小心。所以当你检索它的时候,你会得到它的值。因此,无论何时使用它,都需要检查占位符值。
你的功能会是这样的
function ClickYes() {
// for modern browsers
$('#txtMsg').attr('placeholder', 'Tell me more');
// for older browsers
$('#txtMsg').val('Tell me more');
$('#txtMsg').css('color','#CCC');
}现在您需要处理focus和blur事件,以便像这样完成它
$(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演示
Js Fiddle演示2
发布于 2014-02-19 13:26:21
据我所知,ie9不支持placeholder属性,因此它在IE9中不起作用。
ie9不支持Placehoder属性
您可以按照此链接查看caniuse.com上的兼容性。
因此,您可以尝试以下解决方法:
function ClickYes() {
if(navigator.userAgent.indexOf("MSIE") > 0){
$('#<%=txtMsg.ClientID%>').val('Tell me more');
}else{
$('#<%=txtMsg.ClientID%>').attr('placeholder', 'Tell me more');
}
}发布于 2014-02-19 13:28:12
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
}来源:占位符在IE9中无效
https://stackoverflow.com/questions/21881766
复制相似问题