js修改input的type屬性有些限制。當(dāng)input元素還未插入文檔流之前,是可以修改它的值的,在ie和ff下都沒(méi)問(wèn)題。但如果input已經(jīng)存在于頁(yè)面,其type屬性在ie下就成了只讀屬性了,不可以修改。在ff下仍是可讀寫(xiě)屬性。
今天遇到個(gè)問(wèn)題,輸入框有默認(rèn)值“密碼”,但獲得焦點(diǎn)時(shí),“密碼”兩字會(huì)去掉,輸入時(shí)直接變成”****“的password類型。很明顯,一開(kāi)始的時(shí)候,input的類型是text,后來(lái)變成了password類型。直觀的思路是用js修改input的type類型。但ie下這么做不可行,所以只能換個(gè)思路,寫(xiě)兩個(gè)input,一個(gè)text類型,一個(gè)password類型,分得監(jiān)聽(tīng)onfocus和onblur事件。如下:
注意:script那段代碼要寫(xiě)到html里面
復(fù)制代碼 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿當(dāng)制作</title>
</head>
<style type="text/css">
</style>
<body>
<input type="text" value="密碼" />
<input type="password" />
<script type="text/javascript">
var tx = document.getElementById("tx"), pwd = document.getElementById("pwd");
tx.onfocus = function(){
if(this.value != "密碼") return;
this.style.display = "none";
pwd.style.display = "";
pwd.value = "";
pwd.focus();
}
pwd.onblur = function(){
if(this.value != "") return;
this.style.display = "none";
tx.style.display = "";
tx.value = "密碼";
}
</script>
</body>
</html>
新聞熱點(diǎn)
疑難解答
圖片精選