【发布时间】:2012-12-21 04:43:51
【问题描述】:
我正在尝试为具有 input[type="password"] 的文本框显示占位符文本(输入密码)。现在我正在尝试将 input[type="password"] 更改为 input[type="text"] 以显示占位符,如果用户单击文本框我再次将 input[type="text"] 更改为 input[type="password"]。这里它不起作用,请检查脚本
我的jsfiddle is here
function setupPasswordPlaceholder(thisEl)
{
if('' !== thisEl.attr("alt"))
{
if('' === thisEl.val())
{
thisEl.val(thisEl.attr("alt"));
thisEl.removeAttr("type");
thisEl.attr('type','text');
thisEl.css({'font-weight':'normal','font-size':'10pt','color':'#999','font-family': '"lucida grande", tahoma, verdana, arial, sans-serif'});
}
thisEl.focus(function()
{
if(thisEl.val() == thisEl.attr("alt"))
{
thisEl.val("");
thisEl.removeAttr("type");
thisEl.attr('type','password');
thisEl.css({'color': '#18A505','font-size': '10pt','font-weight':'normal'});
}
});
thisEl.focusout(function()
{
if('' === thisEl.val())
{
thisEl.val(thisEl.attr("alt"));
thisEl.removeAttr("type");
thisEl.attr('type','text');
thisEl.css({'font-weight':'normal','font-size':'10pt','color':'#999','font-family': '"lucida grande", tahoma, verdana, arial, sans-serif'});
}
});
}
}
$("input[type='password']").each(function(){
setupPasswordPlaceholder($(this));
});
【问题讨论】:
-
HTML5 为输入框添加了占位符属性。这对您来说不是一个适当的解决方案吗?
<input type="password" placeholder="Enter Password" /> -
对不起,我用的是html4,这里没有选项,ie6,ie7不支持html5
-
在尝试更改输入元素的类型属性时,DOM 不是很友好。上次我玩这个时,它只有在从 DOM 中分离元素、更改属性然后重新附加它时才成功。充其量只是一个黑客攻击。
标签: javascript jquery