You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

摩尔斯电码翻译器网页端运行异常问题求助

摩尔斯电码翻译器延迟更新问题修复

问题:输入字符后,需额外输入一个字符或空格才能触发翻译结果更新。

问题原因

使用keypress事件时,该事件在字符尚未插入到输入框时就会触发,此时input.value不包含刚输入的字符,导致翻译结果滞后一步。

解决方法

将事件监听替换为input事件——该事件会在输入框内容实际更新后触发,能即时响应所有内容变化(包括键盘输入、粘贴等操作),同时修正未声明变量的问题。

修改后的完整代码

JavaScript代码

let eng = {
    "a": " ._",
    'b': ' _...',
    'c': ' _._.',
    'd': ' _..',
    'e':' .',
    'f': ' .._.',
    'g': ' __.',
};

let input = document.getElementById('input');
let output = document.getElementById('output');
input.addEventListener('input', function(event) {
    const out = eng2mc(input.value);
    output.value = out;
})

function eng2mc(string) {
  let output = "";
  const characters = string.toLowerCase().split("")
  for (let character of characters) {
    if (character === " ") {
      output += "    "  // 4 spaces (+3 of last letter, makes 7)
    } else if(eng[character]){
      output += eng[character] + "   "  // 3 spaces between letters
    }
  }
  return output
}

CSS代码

.boxparent {
    display: flex;
    flex-wrap: wrap;
    margin: auto;
    margin-top: 2%;
    width: 50%;
}

.textbox {
    font-size: .8rem;
    letter-spacing:1px;
    font-family: Palatino Linotype;
    padding:10px;
    line-height:1.5;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow:1.25px 1.25px 1.25px #222222;
    resize: none;
}

#entertext {
    position:absolute;
    font-size:20px;
    margin-left:585px;
    font-family: Palatino Linotype;
}

#input {
    display:inline-block;
    padding:10px;
}

#output {
    position:relative;
    right:-16px;
}

HTML代码

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<head>
    <title>Morse Code Translator</title>
</head>
<link rel="stylesheet" href="main.css">
<style>
body {
    background-color:#555555;
}
</style>
<body>
<br>
<form class="boxparent" method="post">
    <textarea class="textbox" id="input" rows="10" cols="80" placeholder="Enter text here"> </textarea>
    <textarea readonly class="textbox" id="output" rows="10" cols="80"></textarea>
</form>

<script src="main.js"></script>
</body>
</html>

内容的提问来源于stack exchange,提问作者1440p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:39:16