這裏是我的解決方案。我增加了以下內容輸入的標籤和標籤
<label class="label-inside" for="input1" id="input1_label" title="Enter input 1">Input 1</label>
<ul class="form-input">
<li>
<input type="text" id="input1" name="myInput1" value="" autocomplete="off" title="Enter Input 1" onblur="handleBlur(this, document.getElementById('input1_label'))"
onkeydown="handleFirstClick(event, this, document.getElementById('input1_label'))"
onkeyup="handleKey(this, document.getElementById('input1_label'))" />
</li>
</ul>
,這裏是我的JavaScript
<script>
function handleBlur(input, label)
{
if (!input.value || input.value.length == 0)
{
label.style.display = 'block';
label.style.color = 'black';
label.clickedBefore = false;
}
}
function handleFirstClick(e, input, label)
{
if (!label.clickedBefore)
{
label.clickedBefore = true;
e.preventDefault();
label.style.color = 'red';
}
}
function handleKey(input, label)
{
console.log("handling key up : " + input.value.length);
label.style.display = 'none';
if (!input.value || input.value.length == 0)
{
label.style.display = 'block';
label.style.color = 'red';
}
}
</script>
讓我知道,如果需要別的東西。
編輯:添加代碼一次根據input_id添加所有處理程序。
window.onload = function(){
console.log("windows loaded");
var labels = {}
var all_labels = document.getElementsByTagName("label");
for (var i = 0; i < all_labels.length; i++)
{
labels[all_labels[i].getAttribute("for")] = all_labels[i];
}
function attachHandlers(input_id)
{
var input = document.getElementById(input_id);
var label = labels[input_id];
input.onclick = function(e){handleFirstClick(e, input, label)};
input.onkeyup = function(e){handleKey(input, label)};
input.onblur = function(e){handleBlur(input, label)};
}
var attachInput = ["input1"];
for (var j =0; j <attachInput.length; j++)
{
attachHandlers(attachInput[j]);
}
}
我用的「紅」,而不是淺灰色..更容易調試 – 2012-01-03 14:48:38
這裏是[我的小提琴(http://jsfiddle.net/CnBeW/) – 2012-01-03 14:48:56
感謝您的建議的鏈接!我剛剛試圖訪問你的JF,但它似乎並沒有工作.. – JaXL 2012-01-03 15:26:11