Ten kod zwraca integer gdzie?
for (let i = 0; i < number.length; i++)
{
parseInt(number[i].textContent);
}
Proponuje:
- użyć textContent, innerHTML można użyć, ale w tym kontekście interesuje nas tylko sam tekst (zapisana liczba)
- użyć zdarzenia keydown
- użyć Event Delegation [ 1 ] [ 2 ]
Przykład z wykorzystaniem Event Delegation
[ działający kod on-line ]
<style>
/* dla demonstracji */
.stopwatch {
font: 300 2rem/1 system-ui, monospace;
padding: 2rem;
}
[contenteditable] {
outline-offset: .15rem;
outline-color: rgba(0, 255, 0, .4);
padding: .15rem;
letter-spacing: .05rem;
}
[contenteditable]:focus {
animation: pulsate 2s infinite;
}
@keyframes pulsate {
0% {
box-shadow: 0 0 20px rgba(0, 255, 0, 0.8);
}
50% {
box-shadow: 0 0 40px rgba(0, 255, 0, 0.4);
}
100% {
box-shadow: 0 0 20px rgba(0, 255, 0, 0.8);
}
}
</style>
<div class="stopwatch">
<span contenteditable="true" id="stopwatch-hours" class="stopwatch-number">00</span>
<span class="stopwatch-colon">:</span>
<span contenteditable="true" id="stopwatch-minutes" class="stopwatch-number">00</span>
<span class="stopwatch-colon">:</span>
<span contenteditable="true" id="stopwatch-seconds" class="stopwatch-number">00</span>
</div>
<script>
const stopwatch = document.querySelector('.stopwatch'); // dla Event Delegation
function formatNumbers(e) {
e.preventDefault();
const span = e.target;
if (e.code == 'Delete') {
span.textContent = '00';
return;
}
if (/^\d$/.test(e.key)) { // tylko cyfry
const currentValue = span.textContent,
inputValue = e.key;
let newValue = parseInt(currentValue + inputValue);
if (newValue > 99) newValue = newValue.toString().slice(-2);
if (newValue > 59) newValue = inputValue;
span.textContent = ('00' + newValue).slice(-2);
}
}
stopwatch.addEventListener('keydown', formatNumbers);
</script>
[ Simplest inline method to left pad a string ]