js修改input的type屬性問題探討
更新時間:2013年10月12日 10:35:31 作者:
當input元素還未插入文檔流之前,是可以修改它的值的,在ie和ff下都沒問題。但如果input已經(jīng)存在于頁面,其type屬性在ie下就成了只讀屬性了,不可以修改
js修改input的type屬性有些限制。當input元素還未插入文檔流之前,是可以修改它的值的,在ie和ff下都沒問題。但如果input已經(jīng)存在于頁面,其type屬性在ie下就成了只讀屬性了,不可以修改。在ff下仍是可讀寫屬性。
今天遇到個問題,輸入框有默認值“密碼”,但獲得焦點時,“密碼”兩字會去掉,輸入時直接變成”****“的password類型。很明顯,一開始的時候,input的類型是text,后來變成了password類型。直觀的思路是用js修改input的type類型。但ie下這么做不可行,所以只能換個思路,寫兩個input,一個text類型,一個password類型,分得監(jiān)聽onfocus和onblur事件。如下:
注意:script那段代碼要寫到html里面
<!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>阿當制作</title>
</head>
<style type="text/css">
</style>
<body>
<input name="" type="text" value="密碼" class="inputText_1" id="tx" style="width:100px;" />
<input name="" type="password" style="display:none;width:100px;" id="pwd" />
<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>
今天遇到個問題,輸入框有默認值“密碼”,但獲得焦點時,“密碼”兩字會去掉,輸入時直接變成”****“的password類型。很明顯,一開始的時候,input的類型是text,后來變成了password類型。直觀的思路是用js修改input的type類型。但ie下這么做不可行,所以只能換個思路,寫兩個input,一個text類型,一個password類型,分得監(jiān)聽onfocus和onblur事件。如下:
注意:script那段代碼要寫到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>阿當制作</title>
</head>
<style type="text/css">
</style>
<body>
<input name="" type="text" value="密碼" class="inputText_1" id="tx" style="width:100px;" />
<input name="" type="password" style="display:none;width:100px;" id="pwd" />
<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>
相關(guān)文章
Javascript Cookie讀寫刪除操作的函數(shù)
Javascript Cookie讀寫刪除操作的函數(shù)代碼,需要操作cookies的朋友可以參考下。2010-03-03微信小程序如何加載數(shù)據(jù)庫真實數(shù)據(jù)的實現(xiàn)
這篇文章主要介紹了微信小程序如何加載數(shù)據(jù)庫真實數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03教你用js截取字符串開頭、結(jié)尾及兩字符串之間的內(nèi)容
在js中可以通過indexOf()方法找到指定的字符位置,再使用length屬性獲得字符串的長度,下面這篇文章主要給大家介紹了關(guān)于如何用js截取字符串開頭、結(jié)尾及兩字符串之間的內(nèi)容的相關(guān)資料,需要的朋友可以參考下2022-11-11