我正在尝试在我的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