我正在嘗試在我的html聯繫人表單中使用<label>
元素,例如輸入的HTML5佔位符屬性。我寫了下面的JavaScript來充當可重複使用的功能,以提供以下功能。使用HTML5佔位符等標籤
- 按名稱查找輸入。
- 獲取輸入的值。
- 找到屬於輸入的標籤。
- 根據輸入的狀態更改標籤樣式。
- 根據輸入值更改標籤樣式。
但它不工作,我不知道爲什麼,因爲沒有錯誤出現在控制檯。我究竟做錯了什麼? here is a JS Fiddle with code
function placeholder(field_name) {
// Get the input box with field_name
// Then get input value
var box = document.getElementsByName(field_name);
var i;
for (i = 0; i < box.length; i++) {
var value = document.getElementById(box[i].value);
}
// Get the labels belonging to each box using the HTML for attribute
var labels = document.getElementsByTagName('LABEL');
for (i = 0; i < labels.length; i++) {
if (labels[i].htmlFor !== '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem) {
box.label = labels[i];
}
}
}
// Colors
var focusColor = "#D5D5D5";
var blurColor = "#B3B3B3";
// If no text is in the box then show the label grey color
box.onblur = function() {
box.label.style.color = blurColor;
};
// If input focuses change label color to light grey
box.onfocus = function() {
box.label.style.color = focusColor;
};
// If there is text in the box then hide the label
if (box.value !== "") {
// Quick do something, hide!
box.label.style.color = "transparent";
}
}
// Call the function passing field names as parameters
placeholder(document.getElementsByName("email"));
placeholder(document.getElementsByName("firstName"));
placeholder(document.getElementsByName("lastName"));
現在,你如何比較'label'和'placeholders'? – 2013-02-26 12:48:33
'var box = document.getElementsByName(field_name);' - 'box'是一個_NodeList_。 'if(elem)box.label = labels [i];'在_NodeList_上設置新的屬性_label_。此外,內部循環中的'var'讓我感到難過。 – 2013-02-26 12:49:40
@PaulS。他到底在做什麼?他提取佔位符值,但是爲了什麼? 'placeholder(document.getElementsByName(「email」));' – 2013-02-26 12:50:46