Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Таймер обратного счета и стили для кнопок (https://javascript.ru/forum/misc/74147-tajjmer-obratnogo-scheta-i-stili-dlya-knopok.html)

Хомяк 17.06.2018 23:01

Таймер обратного счета и стили для кнопок
 
Здравствуйте :) Подскажите, пожалуйста, как в данном коде правильно реализовать остановку теста по истечении времени? То есть, по истечении времени тест сворачивается и выводится сообщение "время вышло"

И ещё, никак не могу сообразить, как сделать так, чтобы при неправильном ответе, не только выводился комментарий, но и стиль кнопок менялся (правильный ответ - зелёный, неправильный -красный). Сейчас выходит так, что при нажатии на кнопку, сразу перебрасывает на следующий вопрос,а комментарий к предыдущему вопросу, высвечивается уже сверху над новым.Вот как сделать так, чтобы при неправильном ответе, не перебрасывало на новый вопрос, а сначала менялся стиль, выводился комментарий, а потом уже можно было перейти к другому вопросу?

<!DOCTYPE html>
<html lang="ru-RU">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тест на время</title>
<style>
body{
	font-family:verdana;
	color:#444;
}
#option1,#option2,#option3{
	display:none;
	margin-bottom: 10px;
}
.kp{
    text-decoration: none;
    font-size: 20px;
    margin-right: 20px;
    color: #fff;
    background: #333333;
    padding: 4px 8px;
	border: 0;
	cursor: pointer;
}
.nach{
    text-decoration: none;
    font-size: 20px;
    margin-right: 20px;
    color: #fff;
    background: #ff8000;
    padding: 4px 8px;
	border: 0;
	cursor: pointer;
}
</style>
<script type="text/javascript">
     function mix(mixArray) {
      var index, valueIndex; 
      for (var i=0; i<=mixArray.length-1; i++) {
        index = Math.floor(Math.random()*i);
        valueIndex = mixArray[index];
        mixArray[index] = mixArray[i];
        mixArray[i] = valueIndex;
      }
      return mixArray;
    }

	//Массив вопросов и ответа
	var data_array = [
	  ["Сколько сантиметров в метре?","10","1024","100",3,"комм1"],
	  ["Перевод слова: Hello","Как дела?","Привет","Ты",2,"комм2"],
	  ["Перевод слова: Dog","Собака","Кошка","Дерево",1,"комм3"],
	  ["Сколько месяцев в году?","10","11","12",3,"комм4"],
	  ["Перевод слова: Tree","Три","Собака","Дерево",3,"комм5"],
	  ["Перевод слова: Wall","Стена","Дом","Башня",1,"комм6"],
	];
	
    mix(data_array); 
	var plus = 0;
	var time = 60;
	var cur_answer = 0;
	var count_answer = 3;
	var intervalID;
	
	function sec() {
	    if(time<0)
        clearInterval(intervalID);
		time=time-1;	
		document.getElementById('time').innerHTML=time + ' сек';
	}
	
	function check(num){

		if(num == 0){ 
		
			document.getElementById('option1').style.display='block';
			document.getElementById('option2').style.display='block';
			document.getElementById('option3').style.display='block';
			document.getElementById('question').style.display='block';

			document.getElementById('option1').innerHTML=data_array[cur_answer][1];
			document.getElementById('option2').innerHTML=data_array[cur_answer][2];
			document.getElementById('option3').innerHTML=data_array[cur_answer][3];
			document.getElementById('question').innerHTML=data_array[cur_answer][0];
			
			document.getElementById('start').style.display='none';
		
			
			intervalID = setInterval(sec, 1000);
			 
			
		}else{

			if( num ==  data_array[cur_answer][4]){
				plus++;
				
			}else{
			document.getElementById('result').innerHTML="Неверно!" + [data_array[cur_answer][5]];	
			}
				
			cur_answer++;
			if(cur_answer < count_answer){
			
				document.getElementById('option1').innerHTML=data_array[cur_answer][1];
				document.getElementById('option2').innerHTML=data_array[cur_answer][2];
				document.getElementById('option3').innerHTML=data_array[cur_answer][3];
				document.getElementById('question').innerHTML=data_array[cur_answer][0];
				
			}else{
				
				document.getElementById('end').style.display='inline';
				document.getElementById('time').id = 'stop';
				document.getElementById('option1').style.display='none';
				document.getElementById('option2').style.display='none';
				document.getElementById('option3').style.display='none';
				document.getElementById('question').style.display='none';
				
				
				var percent =  Math.round(plus/count_answer*100);				
				var res = 'Плохо!';
				if(percent>70) res = 'Хорошо!';
				if(percent==100) res = 'Отлично!';
				
				document.getElementById('result').innerHTML='Правильных ответов: ' + plus + ' из ' + count_answer + ' (' + percent + '%)<br>' + res;
			}
		}
	}
</script>
</head>
<body>
	<center>			
		<p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="time"></p>
		<p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="result"></p>
					
		<p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="question"></p>
		
		<button onclick="check(1)" class="kp" id="option1"></button>
		
		<button onclick="check(2)" class="kp" id="option2"></button>
		
		<button onclick="check(3)" class="kp" id="option3"></button>
		
	</center><br>
	<center>
		<button id="start" class="kp" onclick="check(0)">Приступить к тесту</button>
		<script type="text/javascript"> var curent_url = document.URL; document.write("<a id='end' style='display: none;' class='nach' href='" + curent_url + "'>Начать сначала</a>"); </script>	
	</center><br><br>
</body>
</html>

Хомяк 17.06.2018 23:05

Если сделать так

Добавить в sec() перед изменением счётчика

if(time<0)
    clearInterval(intervalID);

объявить перед sec()

var intervalID;

и соответственно запускать таймер

intervalID = setInterval(sec, 1000);


То счетчик почему-то останавливается на -2 и тест можно продолжать дальше... Как исправить косяк с -2 и остановить таки тест?

рони 17.06.2018 23:16

Хомяк,
https://javascript.ru/forum/css-html...tml#post369143

Хомяк 17.06.2018 23:41

Спасибо, а если таймер не на каждый вопрос, а общий таймер на выполнение теста?

рони 17.06.2018 23:45

Хомяк,
function sec() {
        if(time<0) clearInterval(intervalID);
        else {
        document.getElementById('time').innerHTML=time + ' сек';
        time=time-1;
        }
    }

рони 17.06.2018 23:48

Хомяк,
function sec() {
        if(time<0) {
          clearInterval(intervalID);
          cur_answer = count_answer;
          check()
        }
        else {
        document.getElementById('time').innerHTML=time + ' сек';
        time=time-1;

        }
    }

Хомяк 18.06.2018 00:06

Спасибо большое! :dance:
А насчет смены стиля не подскажете?

рони 18.06.2018 00:09

Хомяк,
<!DOCTYPE html>
<html lang="ru-RU">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тест на время</title>
<style>
body{
    font-family:verdana;
    color:#444;
}
#option1,#option2,#option3{
    display:none;
    margin-bottom: 10px;
}
.kp{
    text-decoration: none;
    font-size: 20px;
    margin-right: 20px;
    color: #fff;
    background: #333333;
    padding: 4px 8px;
    border: 0;
    cursor: pointer;
}
.nach{
    text-decoration: none;
    font-size: 20px;
    margin-right: 20px;
    color: #fff;
    background: #ff8000;
    padding: 4px 8px;
    border: 0;
    cursor: pointer;
}
</style>
<script type="text/javascript">
     function mix(mixArray) {
      var index, valueIndex;
      for (var i=0; i<=mixArray.length-1; i++) {
        index = Math.floor(Math.random()*i);
        valueIndex = mixArray[index];
        mixArray[index] = mixArray[i];
        mixArray[i] = valueIndex;
      }
      return mixArray;
    }

    //Массив вопросов и ответа
    var data_array = [
      ["Сколько сантиметров в метре?","10","1024","100",3,"комм1"],
      ["Перевод слова: Hello","Как дела?","Привет","Ты",2,"комм2"],
      ["Перевод слова: Dog","Собака","Кошка","Дерево",1,"комм3"],
      ["Сколько месяцев в году?","10","11","12",3,"комм4"],
      ["Перевод слова: Tree","Три","Собака","Дерево",3,"комм5"],
      ["Перевод слова: Wall","Стена","Дом","Башня",1,"комм6"],
    ];

    mix(data_array);
    var plus = 0;
    var time = 60;
    var cur_answer = 0;
    var count_answer = 3;
    var intervalID;

    function sec() {
        if(time<0) {
          window.clearTimeout(intervalID);
          cur_answer = count_answer;
          check()
        }
        else {
        document.getElementById('time').innerHTML=time + ' сек';
        time=time-1;
        intervalID = window.setTimeout(sec,1000);
        }
    }
function check(num) {
  if (num == 0) {
    document.getElementById("option1").style.display = "block";
    document.getElementById("option2").style.display = "block";
    document.getElementById("option3").style.display = "block";
    document.getElementById("question").style.display = "block";
    document.getElementById("option1").innerHTML = data_array[cur_answer][1];
    document.getElementById("option2").innerHTML = data_array[cur_answer][2];
    document.getElementById("option3").innerHTML = data_array[cur_answer][3];
    document.getElementById("question").innerHTML = data_array[cur_answer][0];
    document.getElementById("start").style.display = "none";
    sec();
  } else {
    if (num == data_array[cur_answer][4]) {
      plus++;
    }
    cur_answer++;
    if (cur_answer < count_answer) {
      document.getElementById("option1").innerHTML = data_array[cur_answer][1];
      document.getElementById("option2").innerHTML = data_array[cur_answer][2];
      document.getElementById("option3").innerHTML = data_array[cur_answer][3];
      document.getElementById("question").innerHTML = data_array[cur_answer][0];
    } else {
      document.getElementById("end").style.display = "inline";
      time = -1;
      document.getElementById("option1").style.display = "none";
      document.getElementById("option2").style.display = "none";
      document.getElementById("option3").style.display = "none";
      document.getElementById("question").style.display = "none";
      var percent = Math.round(plus / count_answer * 100);
      var percent =  Math.round(plus/count_answer*100);
      var res = 'Плохо!';
      if(percent>70) res = 'Хорошо!';
      if(percent==100) res = 'Отлично!';
      document.getElementById('result').innerHTML='Правильных ответов: ' + plus + ' из ' + count_answer + ' (' + percent + '%)<br>' + res;    }
  }
};
</script>
</head>
<body>
    <center>
        <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="time"></p>
        <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="result"></p>

        <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="question"></p>

        <button onclick="check(1)" class="kp" id="option1"></button>

        <button onclick="check(2)" class="kp" id="option2"></button>

        <button onclick="check(3)" class="kp" id="option3"></button>

    </center><br>
    <center>
        <button id="start" class="kp" onclick="check(0)">Приступить к тесту</button>
        <script type="text/javascript"> var curent_url = document.URL; document.write("<a id='end' style='display: none;' class='nach' href='" + curent_url + "'>Начать сначала</a>"); </script>
    </center><br><br>
</body>
</html>

Хомяк 18.06.2018 00:18

С таймером получилось и так, как вы в первый раз написали :blink:

Хомяк 18.06.2018 00:23

Подскажите, пожалуйста, как при неверном ответе менять стили кнопок (таймер тут уже не нужен).
То есть, если пользователь отвечает неправильно, выводится комментарий, вот таким способом
if( num ==  data_array[cur_answer][4]){
				plus++;
			
			}	
			else{
            document.getElementById('result').innerHTML="Неверно!" + [data_array[cur_answer][5]];
            }


Хотелось бы ещё, чтоб у кнопки, которую он выбрал цвет поменялся на красный, а кнопка с правильным ответом стала зелёной, как это можно реализовать?


Часовой пояс GMT +3, время: 03:33.