有的浏览器不支持placeholder这个属性,所以我们只能通过代码去模仿出placeholder的样子,让他看上去像是placeholder。
这个思路是在网上看到的,但是我这用不了,所以我就自己改进了一点。
具体代码如下:
function placeholderSupport() {
return 'placeholder' in document.createElement('input');
}
function solvePlaceholder(selector){
if(!placeholderSupport()){
var array=$(selector);
array.each(function(){
$(this).addClass('placeholder');
$(this).val($(this).attr('placeholder'));
});
array.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();
}
}
placeholderSupport这个方法是判断浏览器的input标签支不支持placeholder这个属性,我们会在solvePlaceholder调用。在solvePlaceholder判断完毕后,如果不支持,我们就先赋值,然后根据鼠标focus和blur事件来展示出不同的效果。solvePlaceholder的参数selector是选择器,比如有好几个input,就可以用组选择器春进去,要是一个input你只需要传一个比如: solvePlaceholder('#modelCode,#modelName,#warnInfo,#showSeqNo');
而且这两个方法要灵活的去运用,根据你们不同的业务逻辑。