網上有好多關於這方面解決兼容性問題的文章,很多招式,學會這一招,讓你輕松搞定Placeholder的兼容性,叫我好人,拿走,不謝。。。。
placeholder屬性是HTML5 中為input添加的。在input上提供一個占位符,文字形式展示輸入字段預期值的提示信息(hint),該字段會在輸入為空時顯示。
如
<input type="text" id="Title" class="so-input-d w270" placeholder="請輸入標題" />
像下圖用placeholder剛剛好,但是IE6 7 8 9 不支持呀,一篇空白!此時此刻心情肯定是日了狗!!!!!,搞web開發的一定要考慮兼容性,業界良心需要。。。。
使用前:

使用后:

療效不一般,使用之后萌萌噠。
目前瀏覽器的支持情況:
| 瀏覽器 | IE6/7/8/9 | IE10+ | Firefox | Chrome | Safari |
| 是否支持 | NO | YES | YES | YES | YES |
下面分享一個Js文件代碼,簡單粗暴的把問題解決了:
(function ($) {
$.fn.myPlaceholder = function (options) {
var defaults = {
pColor: "#acacac",
pFont: "16px",
posL: 8,
zIndex: "99"
},
opts = $.extend(true, defaults, options);
if ("placeholder" in document.createElement("input")) return;
return this.each(function () {
//$(this).parent().css("position", "relative");
var isIE = $.browser.msie,
version = $.browser.version;
//不支持placeholder的瀏覽器
var $this = $(this),
msg = $this.attr("placeholder"),
iH = $this.outerHeight(),
iW = $this.outerWidth(),
iX = $this.offset().left,
iY = $this.offset().top,
oInput = $("<label>", {
"text": msg,
"css": {
"position": "absolute",
"left": iX + "px",
"top": iY + "px",
"width": iW - opts.posL + "px",
"padding-left": opts.posL + "px",
"height": iH + "px",
"line-height": iH + "px",
"color": opts.pColor,
"font-size": opts.pFont,
"z-index": opts.zIndex,
"cursor": "text"
}
}).insertBefore($this);
//初始狀態就有內容
var value = $this.val();
if (value.length > 0) {
oInput.hide();
};
var myEvent;
if (isIE && version < 9) {
myEvent = "propertychange";
} else {
myEvent = "input";
}
$this.bind(myEvent, function () {
var value = $(this).val();
if (value.length > 0) {
oInput.hide();
} else {
oInput.show();
}
});
oInput.click(function () {
$this.trigger("focus");
});
});
}
})(jQuery);
這是用JQUERY插件化思想的解決的!
在頁面或者操作的Js文件只用這樣輕輕一搞:
$(function () {
$("#Title").myPlaceholder();
});
Placeholder兼容問題就解決了(文章標紅的地方注意ID一致)!
抓緊有限的時間,燥起來!
