Как прочитать текст во входном теге в теге ap? - PullRequest
0 голосов
/ 23 ноября 2018

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);
}

Когда я вводю некоторый текст в поле ввода, код по-прежнему гласит «заполнитель ...», как сделатькод для ввода введенного текста?

1 Ответ

0 голосов
/ 23 ноября 2018

Вы захватываете innerHTML, который не будет читать text, он будет читать html.

Для того, чтобы объединить ваши input элементы и ваши text,вам на самом деле нужно объединить эти два кода в вашем коде.Вероятно, в функции speak.

Простейший способ сделать это, вероятно, следующий:

let compiledStr = "";
inputTxt.childNodes.forEach(i =>
compiledStr += (i.nodeType === 3) ? 
  i.textContent : 
  i.value);

То, что сделано выше, это итерация по дочерним узлам элемента inputTxt,Он захватывает textContent (обычный текст) любого text nodes или 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>

Для вашего текущего кода должно работать следующее:

let synth = window.speechSynthesis;
let inputTxt = document.getElementById('txt');


function speak() {
let inputTxt = document.getElementById('txt');

let compiledStr = "";
inputTxt.childNodes.forEach(i => compiledStr += (i.nodeType === 3) ? i.textContent : i.value);

if (synth.speaking) {
    console.error('speechSynthesis.speaking');
    return;
}
    let utterThis = new SpeechSynthesisUtterance(compiledStr);

    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);
}
<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>
...