我用JavaScript创建了一个秒表.当用户输入要提醒的时间时,我想添加一个声音



我是一个新手,正在努力学习。我用HTML和js创建了一个Start-stop watch。我想添加一个输入字段,让用户输入时间以及何时播放声音。

我试着制作一个变量并试图获得输入数据,但我只是把一切都搞砸了。我试着在YouTube和谷歌上查找,但似乎找不到任何答案。

谢谢你抽出时间。下面是我的代码。

<div class="controls">
<button onclick="start()">Start</button>
<button onclick="pause()">Pause</button>
<button onclick="stop()">Stop</button>
<button onclick="restart()">Restart</button>
<button onclick="lap()">Lap</button>
<button onclick="resetLaps()">Reset Laps</button>
</div>
<div class="stopwatch">
00:00:00
</div>
<input type="text" id="inputVal"><button onclick="getVal()">Set Time</button>
<ul class="laps"></ul>
<audio id="ado" src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" controls="true"></audio>

下面是Javascript。

<script type="text/javascript">
var ms = 0, s = 0, m = 0;
var timer;
var stopwatchEL = document.querySelector('.stopwatch');
var lapsContainer = document.querySelector('.laps');
function start(){
if(!timer){
timer = setInterval(run, 10)


}


}
function run(){
stopwatchEL.textContent = getTimer();
ms++;

updateTimer(); 
if(ms == 100){
ms = 00;
s++

}
if(s == 60){
s = 0;
m++;
}

}
function pause(){
stopTimer();
}
function stop(){
stopTimer();
m = 0;
ms = 0;
s = 0;
stopwatchEL.textContent = getTimer();

}
function getTimer(){
return (m < 10 ? "0" + m:m) + ":" + (s < 10 ? "0" + s:s) + ":" + (ms < 10 ? "0" + ms:ms);
}
function stopTimer(){
clearInterval(timer);
timer = false;
}
function restart(){
stop();
start();
}
function lap(){
if(timer){
var li = document.createElement('li');
li.innerText = getTimer();
lapsContainer.appendChild(li);

}
}
function resetLaps() {
lapsContainer.innerHTML = "";
}


function getVal(){
var inputVal = document.getElementById('inputVal').value;

}
function updateTimer() {

if(m == 0, ms == 0, s == inputVal){
$('#ado').get(0).play();
pause();
}
}
</script>

再次感谢。

如@Denhell所述,首先需要全局inputVal。

var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}

其次,函数updateTimer需要在inputVal和定时器的实际时间之间进行比较。为了播放声音,我把你的jQuery代码转移到了vanillaJS。

function updateTimer() {
if(getTimer() == inputVal){
document.getElementById('ado').play();
pause();
}
}

在函数中,运行必须在结束时执行updateTimer的调用,否则比较值在新的一秒或一分钟开始时(例如00:13:00(无法正常工作。

function run(){
stopwatchEL.textContent = getTimer();
ms++;

if(ms == 100){
ms = 0;
s++;
}
if(s == 60){
s = 0;
m++;
}
updateTimer();     
}

唯一的问题是,计时器停止正确,但不会更新最后一个毫秒。为此,你可以看看自己。对于我的解决方案,手动设置的时间必须为mm:ss:ms格式,所有三个值都是2位数,如01:17:09

你可以在这里试试:https://jsfiddle.net/8w67uy5a/5/

您在getVal函数中声明了一个其他函数不知道的变量inputVal。使用类似的东西

var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}

这将解决您的问题。

<audio id="ado">
<source src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" type="audio/mpeg"></source>
</audio>
function getVal() {
const sound = document.getElementById("ado");
sound.play();
var inputVal = document.getElementById("inputVal").value;
}

最新更新