0

请您就以下问题提供建议:

我有一个注册表单,其中有一个文本区域

<form id="register" name="register" method="post" action="register.php">

<textarea rows="5" id="bio" name="bio" method="post">Biographical information</textarea>

</form>

使用 java 脚本,我一直在尝试为 onfocus 和 onblur 事件创建一个事件处理程序,以便在焦点上删除默认文本并在模糊时恢复,如下所示:

var bioField = document.getElementById("bio");

bioField.onfocus = function() {
    if (bioField.value == "Biographical information") {
        bioField.value = "";
    }
};

bioField.onblur = function() {
    if (bioField.value == "") {
        bioField.value = "Biographical information";
    }
};

我认为通过 id 获取元素会起作用,但似乎不是。不存在其他名称/身份重复。

非常感谢任何帮助。多谢你们

4

4 回答 4

1

使用占位符属性:

<textarea rows="5" id="bio" name="bio" method="post" placeholder="Biographical information"></textarea>
于 2013-01-17T16:10:29.250 回答
0

它工作正常,也许问题是占位符默认为“传记信息”,而脚本正在测试“关于你的一切”。您在我发布此内容时所做的更改正是您所需要的。

var bioField = document.getElementById("bio");

bioField.onfocus = function() {
    if (bioField.value == "Biographical information") {
        bioField.value = "";
    }
};

bioField.onblur = function() {
    if (bioField.value == "") {
        bioField.value = "Biographical information";
    }
};

http://jsfiddle.net/YeaTQ/1/

于 2013-01-17T16:14:53.830 回答
0

You have two solutions:

  1. In order to not use the javascript code you wrote, Use the following code:

    <textarea cols="30" rows="5" id="bio" name="bio" onfocus="this.value = '' " onblur="this.value = 'All about you'">Biographical information</textarea>

  2. I think the javascript code is located before control (in the header I guess), Because of this, the onfocus and onblur properties are not initialized. You'll have to put the script at the end of the document (before the tag).
    Also, you script is searching for another text ("All about you") and not the current text that's inside ("Biographical information"). Even if you insert the javascript code at the of the document, the code it will work.

于 2013-01-17T17:31:12.680 回答
0

我有根据的猜测是,您已将代码按原样放入<script>内部标签中,<head>因此当脚本运行时,表单尚未加载。

将您<script>的表格移到表格下方或使用以下内容包装所有内容window.onload

window.onload = function(){
   // Code goes here
};
于 2013-01-17T16:20:58.547 回答