我工作的一些东西,可以让你更新页面中的文本。有一个提交按钮,它上面更新的文本框中。触发它的另一种方式是与文本框里面输入时的回车键。
什么是应该发生的时候,“发送”按钮或回车键被按下,即文本将在文本框中去。问题是,在使用时,该文本框上方也将被删除,文本闪烁上有一秒钟。如何让这个文字在上面文本框中说吗?
下面是代码:
<html>
<head>
<script type = "text/javascript">
function SendMsg() {
document.getElementById('ScrollBox').innerHTML = document.send.msg.value + "<br />" + "<br />" + document.getElementById('ScrollBox').innerHTML;
document.getElementById('TextInputBox').value = "";
}
</script>
</head>
<body>
<div id = "ScrollBox" style="height:480px;width:240px;border:1px solid #ccc;overflow:auto;"></div>
<form name = "send" action = "">
: <input type = "text" id = "TextInputBox" title = "Type what you want to send" name = "msg" onkeydown = "if (event.keyCode == 13)
SendMsg()"/>
<input type = "submit" id = "btnSend" value = "Send" onclick = "SendMsg();"/>
</form>
</body>
</html>
奖金是,如果有一种方法,使光标回到文本输入每次提交的时候。
我很新的JavaScript的,这是我的第一个项目,所以我很不清楚如何着手。
非常感谢您的帮助。
作为@插孔巴什福德说,你的表单提交导致页面刷新。对于你想做什么,你实际上并不需要一个形式,所以,除非你的数据实际提交到某个地方我建议删除它。
尝试这个:
<html>
<body>
<div id="ScrollBox" style="height:480px;width:240px;border:1px solid #ccc;overflow:auto;"></div>
: <input type="text" id="TextInputBox" title="Type what you want to send" name="msg" onkeydown="if (event.keyCode == 13) SendMsg();"/>
<input type="button" id="btnSend" value="Send" onclick="SendMsg();"/>
<script>
function SendMsg() {
document.getElementById('ScrollBox').innerHTML = document.getElementById("TextInputBox").value + "<br />" + "<br />" + document.getElementById('ScrollBox').innerHTML;
document.getElementById('TextInputBox').value = "";
}
</script>
</body>
</html>
你的形式提交,如果没有action
给出它默认刷新页面。添加事件侦听器,以防止这种情况的发生:
document.querySelector("form").addEventListener("submit", e => e.preventDefault());
问题是,您使用的是提交输入。因为它迫使重载这将打破你的页面。
见下面更新。增加后的值还增加.focus()在你的TextInput。
<html>
<head>
<script type = "text/javascript">
function SendMsg() {
document.getElementById('ScrollBox').innerHTML = document.send.msg.value + "<br />" + "<br />" + document.getElementById('ScrollBox').innerHTML;
document.getElementById('TextInputBox').value = "";
document.getElementById("TextInputBox").focus();
}
</script>
</head>
<body>
<div id = "ScrollBox" style="height:480px;width:240px;border:1px solid #ccc;overflow:auto;"></div>
<form name = "send" action = "">
: <input type = "text" id = "TextInputBox" title = "Type what you want to send" name = "msg" onkeydown = "if (event.keyCode == 13)
SendMsg()"/>
<input type = "button" id = "btnSend" value = "Send" onclick = "SendMsg();"/>
</form>
</body>
</html>