html 5 有個很棒的屬性,placeholder,在鼠標聚焦到上面時候,提示文字會消失,失去焦點之后,又會出現(xiàn):
但是在不支持html5的低版本的瀏覽器中,placeholder屬性是無效的,為了解決這個問題,因此,人為的去實現(xiàn)placeholder屬性:
復制代碼代碼如下:
//placeholder功能實現(xiàn)
var placeholder = {
add: function (el) {
if (!(’placeholder’ in document.createElement(’input’))) {
var self = placeholder;
el.each(function (e) {
if (IsEmpty(e.value()) || e.value() == e.attr(’placeholder’)) {
e.value(e.attr(’placeholder’));
e.css(’color’, ’gray’);
}
else {
e.css(’color’, ’black’);
}
});
el.bind(’focus’, self._onfocus);
el.bind(’click’, self._onfocus);
el.bind(’blur’, self._onblur);
el.bind(’keyup’, self._onkeyup);
}
},
remove: function (el) {
if (!(’placeholder’ in document.createElement(’input’))) {
var self = placeholder;
el.unbind(’focus’, self._onfocus);
el.unbind(’click’, self._onfocus);
el.unbind(’blur’, self._onblur);
}
},
check: function (el) {
if (!(’placeholder’ in document.createElement(’input’))) {
el.each(function (tar) {
if (IsEmpty(tar.value())) {
tar.value(tar.attr(’placeholder’));
}
});
}
},
clear: function () {
if (!(’placeholder’ in document.createElement(’input’))) {
$(’input[type="text"]’).each(function (el) {
if (el.value() == el.attr(’placeholder’)) {
el.value(’’);
}
});
$(’textarea’).each(function (el) {
if (el.value() == el.attr(’placeholder’)) {
el.value(’’);
}
});
}
},
_onfocus: function () {
if ($(this).value() == $(this).attr(’placeholder’))
$(this).value(’’);
},
_onblur: function () {
if (IsEmpty($(this).value()) || $(this).value() == $(this).attr(’placeholder’)) {
$(this).value($(this).attr(’placeholder’));
$(this).css(’color’, ’gray’);
}
else {
$(this).css(’color’, ’black’);
}
},
_onkeyup: function () {
if (IsEmpty($(this).value())) {
$(this).css(’color’, ’gray’);
}
else {
$(this).css(’color’, ’black’);
}
}
};
使用時候:
復制代碼代碼如下:
placeholder.add($(’input[type="text"]’));
placeholder.add($(’textarea’));
需要注意的是,考慮到如果input的type是password的時候,placeholder顯示的是.....的屬性
這種情況下,解決方法為:
給定兩個輸入框,
一個是text,一個為password的,
在有焦點的時候,切換為password,失去焦點的時候,切換為text用來展示placeholder屬性.
復制代碼代碼如下:
script type="text/javascript" src="/images/defaultpic.gif"/script
script type="text/javascript"
$(function(){
var pwd = $("#pwd");
var password = $("#password");
pwd.focus(function(){
pwd.hide();
password.show().focus();
});
password.focusout(function(){
if(password.val().trim() === ""){
password.hide();
pwd.show();
}
});
});
/script
input type="text" id="pwd" value="https://www.rkxy.com.cn/dnjc/請輸入密碼"/
input type="password" id="password" style="display:none;"/
推薦閱讀
- 千足銀是純銀嗎
- 屬羊大日如來佩戴禁忌
- ie8下不解析background屬性與書寫格式有關(guān)
- css padding屬性兼容ie6,ie8,firefox實例詳解
- 西印度群島的氣候?qū)偈裁?
- 安寧市屬于哪個市
- 哈弗屬于哪個品牌
- 1974年屬虎男有幾次婚姻
- 西瓜屬于哪個溫度帶的水果
- 廣通北站屬于哪里
