0

我需要播放一些文本,然后才执行以下操作(例如隐藏“暂停”和“停止”按钮),但是当我开始播放文本时它们会立即隐藏。简化情况 - 见代码。

非常感谢您的建议。。

<!DOCTYPE html>
<html>
<body>

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<script>

function Voice(id){
    var element = document.getElementById(id);
    var text = element.innerText;
    responsiveVoice.speak(text, "UK English Male", {onend: Hide("div1")});
}

function Hide(id){
    var element = document.getElementById(id);
    element.style="visibility: hidden";
}

</script>

<div id="div1">This is the first line.</div>

<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
 
</body>
</html>

解决方案是使用箭头: {onend: () => Hide()} 而不是 {onend: Hide()} (感谢CertainPerformance)。

onstart:、onend: 和 rate: 甚至可以同时使用。只有一个小问题——更改页面内容后,第一次使用 ResponsiveVoice 功能时延迟较长。见代码:

<!DOCTYPE html>
<html>
<body> 

<script src='https://code.responsivevoice.org/responsivevoice.js'>
</script>

<script>

function Read(id){
    var element = document.getElementById(id);
    var text = element.innerText;
    responsiveVoice.speak(text, "UK English Male", {rate: 1.3, onstart: () => Show(), onend: () => Hide()});
}

function Show(){
    var element = document.getElementById("Pause");
    element.style="visibility: visible";
}

function Hide(){
    var element = document.getElementById("Pause");
    element.style="visibility: hidden";
}

</script>

<div id="div" onclick = 'Read("div")'>This is text to read.</div>
<br>
<input type = "button"
    id = "Pause"
    value = "Pause"
    style = "visibility: hidden" />
     
</body>
</html>
   

4

1 回答 1

0

您需要传递一个调用 Hide的函数,而不是Hide立即调用:

{onend: Hide("div1")}

hide评估该行后立即调用。它需要是:

{onend: () => Hide("div1")}

<!DOCTYPE html>
<html>
<body>

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<script>

function Voice(id){
    var element = document.getElementById(id);
    var text = element.innerText;
    responsiveVoice.speak(text, "UK English Male", {onend: () => Hide("div1")});
}

function Hide(id){
    var element = document.getElementById(id);
    element.style="visibility: hidden";
}

</script>

<div id="div1">This is the first line.</div>

<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
 
</body>
</html>

于 2020-10-18T23:47:46.137 回答