如何在此文本框的开头添加字符串并将其设置为只读,然后允许用户在其前面输入文本?
下面是我的代码:<textarea style="width: 387px; height: 17px;" rows="3" class="do_input" name="job_title" cols="40"></textarea>
目前它是一个普通的文本框,你可以在里面输入任何东西。
我想要的是这样的:
I WILL: demo text
所以I Will: Will是只读的,并且是灰色的,用户输入的文本将在它的前面。
这很容易用一点JavaScript实现。
在文本区域的HTML中添加一个id,例如id="myTextArea"
,如下所示:
<textarea style="width: 387px; height: 17px;" rows="3" class="do_input" name="job_title" cols="40" id="myTextArea"></textarea>
然后,在页面的某个地方或标题部分添加以下JavaScript:
readOnlyString = "I WILL: "
myTextArea = document.getElementById("myTextArea");
myTextArea.value = readOnlyString;
preservedText = readOnlyString;
// Check the value only when the textarea is focused and after the user presses a key
myTextArea.onfocus = function () {
document.onkeyup = function (e) {
updatedText = myTextArea.value;
if (updatedText.indexOf(readOnlyString) == -1)
{
myTextArea.value = preservedText;
}
preservedText = myTextArea.value;
};
};
你可以在这里查看JSFiddle如果你想摆弄它
我想你要找的是占位符属性http://www.w3schools.com/tags/att_input_placeholder.asp
,我想你也在寻找readonly属性http://www.w3schools.com/tags/att_input_readonly.asp