HTML:
<div class="container">
<p class="section-description" id="txt">Today I went to the zoo. I saw a(n) <input placeholder="noun"> <input placeholder="adjective"> jumping up and down in its tree. He <input placeholder="verb, past tense"> <input placeholder="adverb"> through the large tunnel that led to its <input placeholder="adjective"> <input placeholder="noun">. I got some peanuts and passed them through the cage to a gigantic gray <input placeholder="noun"> towering above my head. Feeding that animal made me. </p>
</div>
JS:
let synth = window.speechSynthesis;
let inputTxt = document.getElementById('txt');
function speak() {
if (synth.speaking) {
console.error('speechSynthesis.speaking');
return;
}
let utterThis = new SpeechSynthesisUtterance(inputTxt.innerHTML);
let selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (i = 0; i < voices.length; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
synth.speak(utterThis);
}
当我在输入框中输入一些文本时,代码仍显示为“占位符...”。如何使代码说出所输入的文本?
答案 0 :(得分:0)
您正在抓取innerHTML
,它不会读text
,它将要读html
。
为了连接您的input
元素和text
,您实际上需要在代码中的某处将两者结合起来。可能在speak
函数中。
最简单的方法可能是以下方法:
let compiledStr = "";
inputTxt.childNodes.forEach(i =>
compiledStr += (i.nodeType === 3) ?
i.textContent :
i.value);
以上操作是对inputTxt
元素的子节点进行迭代。它会抓住任何textContent
的{{1}}(纯文本)或任何text nodes
的{{1}}并将它们按顺序缝合在一起。
了解其工作原理的简单示例 请确保单击输入句子下方的“编译”按钮
value
element nodes
以下内容适用于您使用当前代码的情况:
let synth = window.speechSynthesis;
let inputTxt = document.getElementById('txt');
document.querySelector("button").addEventListener("click", function() {
let compiledStr = "";
inputTxt.childNodes.forEach(i => compiledStr += (i.nodeType === 3) ? i.textContent : i.value);
console.log(compiledStr);
});
<div class="container">
<p class="section-description" id="txt">Today I went to the zoo. I saw a(n) <input placeholder="noun" id="noun1"> <input placeholder="adjective" id="adjective1"> jumping up and down in its tree. He <input placeholder="verb, past tense" id="verb1"> <input placeholder="adverb" id="adverb1"> through the large tunnel that led to its <input placeholder="adjective" id="adjective2"> <input placeholder="noun" id="noun2">. I got some peanuts and passed them through the cage to a gigantic gray <input placeholder="noun" id="noun3"> towering above my head. Feeding that animal made me. </p>
</div>
<hr>
<button>Click Me to Compile</button>