Время не отображается при запуске таймера - PullRequest
0 голосов
/ 11 февраля 2020

Мой таймер не показывает, когда я ввожу определенное время, и я несколько раз проверял, в чем проблема, но ошибок нет. Я не уверен, связано ли это с кодом javascript.

Все остальное работает отлично, например, кнопки для отправки, продолжения и остановки.

Это код HTML :

<!DOCTYPE html>
<html>
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>

Это код javascript:

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('.seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    toCount = this.value;
    if(stat.id == "start"){
        display("stop");
        remove("start");
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
    }
    else{
        display("stop");
        remove("continue");
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);


    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}   

Это код CSS:

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #fff;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #fff;
}

Ответы [ 3 ]

1 голос
/ 11 февраля 2020

Ваш селектор неверен: const secInput = document.getElementById ('. Секунд'); используйте "." для занятий. измените эту строку следующим образом: const secInput = document.getElementById ('seconds');

После редактирования: ОК. взгляните на следующий фрагмент: использование переменной toCount было неправильным.

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false;
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);


    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}   
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #fff;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #fff;
}
<head>
    <title>CountDown</title> 
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
   
</body>

Ваш селектор неверен: const secInput = document.getElementById ('. Секунд'); используйте "." для занятий. измените эту строку следующим образом: const secInput = document.getElementById ('seconds');

0 голосов
/ 11 февраля 2020

Вам нужно обновить только несколько вещей:

function check(stat){
    toCount = stat.value;
    // not this.value

const secInput = document.getElementById('seconds');
// not const secInput = document.getElementById('.seconds');

Этого достаточно, чтобы все заработало. Совет: если вы не уверены в значении переменной во время выполнения, вы можете попробовать console.log. В Firefox, Chrome вы можете go для инструментов разработчика - инспектор, вкладка консоли для просмотра результата.

Это то, что я сделал:

function check(stat){
    toCount = this.value;
    console.log(toCount);

Это показало мне, что toCount было неопределенным, а не значение, которое я ожидал, и дало мне понять, что «this» здесь недопустимо, речь идет о переданный объект "stat".

0 голосов
/ 11 февраля 2020

Вот исправление, которое должно заставить ваш код работать

function check(stat){
    seconds = Number(document.getElementById('seconds').value);
    if(stat.id == "start"){
        display("stop");
        remove("start");
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
    }
    else{
        display("stop");
        remove("continue");
    }
    counting();
}
  • вы должны читать значение внутри проверки. Также, когда вы используете getElementById, не используйте (.seconds) be document.getElementById ('seconds')

  • Подсчет вызовов внутри функции проверки для начала подсчета

  • В функции подсчета установите флаг toCount = true
  • Установите флаг toCount = false, когда 'DONE'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...