Попытка создать цифровой отсчет 3.2.1 с помощью JavaScript и CSS - PullRequest
0 голосов
/ 05 мая 2018

var readyGo = document.getElementById("readyGo");

setTimeout(three,1000);

function three(){
    var san = document.createElement("p");
    san.textContent = "three"
    san.className = "three nums";
    readyGo.appendChild(san);
}

setTimeout(two, 2000);

function two(){
    var ni = document.createElement("p");
    ni.textContent = "two";
    ni.className = "two nums";
    readyGo.appendChild(ni);
}

setTimeout(one, 3000);

function one(){
    var ichi = document.createElement("p");
    ichi.textContent = "one";
    ichi.className = "one nums";
    readyGo.appendChild(ichi);
}
#readyGo {
    position:relative;
}

@-webkit-keyframes count {
    0% {transform: scale(1.5);}
    100% {transform: scale(1);}
}

.nums {
    font-size:5rem;
    height:auto;
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
    text-align:center;
}

.three {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}

.two {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}

.one {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}
 <div id="readyGo"></div>

Привет, я пытаюсь создать отсчет 3-2-1 с помощью анимации JavaScript и CSS. Это приведет к началу игры. Предполагается, что вновь созданные элементы, показанные в примере, будут "img" , но я заменил элементы "p" , чтобы они были видны. Таким образом, проблема у меня заключается в том, что я не могу найти способ показывать по одному за раз или заставлять каждого заменять друг друга каждый раз, когда появляется следующий. Я пробовал отображать и отображать анимации, размещая их после анимации «считать», но я не думаю, что должен это делать? Я чувствую, что есть более простой или более продуктивный способ достижения результата. Спасибо, что прочитали код и мой пост.

1 Ответ

0 голосов
/ 05 мая 2018

Я думаю, что вам лучше с интервалом, и вам нужно проверять, чтобы каждый раз удалять ранее созданный абзац. Я использую shift, чтобы вытолкнуть из него первый оставшийся элемент массива, а затем распечатать его. В следующий раз, когда функция вызывается, она может повторять этот шаблон до тех пор, пока не выполнит:

function countdown( parent, callback ){
  
  // This is the function we will call every 1000 ms using setInterval
  
  function count(){

    if( paragraph ){
      
      // Remove the paragraph if there is one
      paragraph.remove();

    }

    if( texts.length === 0 ){
      
      // If we ran out of text, use the callback to get started
      // Also, remove the interval
      // Also, return since we dont want this function to run anymore.
      clearInterval( interval );
      callback();
      return;

    }
  
    // Get the first item of the array out of the array.
    // Your array is now one item shorter.
    var text = texts.shift();
  
    // Create a paragraph to add to the DOM
    // This new paragraph will trigger an animation
    paragraph = document.createElement("p");
    paragraph.textContent = text;
    paragraph.className = text + " nums";

    parent.appendChild( paragraph );

  }
  
  // These are all the text we want to display
  var texts = ['three', 'two', 'one'];
  
  // This will store the paragraph we are currently displaying
  var paragraph = null;
  
  // Initiate an interval, but store it in a variable so we can remove it later.
  var interval = setInterval( count, 1000 );

}

// Start a countdown by passing in the parentnode you want to use.
// Also add a callback, where you start your game.
countdown( document.getElementById("readyGo"), function(){
  
  document.getElementById("readyGo").innerHTML = '<p class="nums">start</p>';
  
});
#readyGo {
    position:relative;
}

@keyframes count {
    0% { transform: scale(1.5); }
    100% { transform: scale(1); }
}

.nums {

    font-size: 5rem;
    height: auto;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    text-align: center;
    animation: count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    
}
<div id="readyGo"></div>

Хотя мы можем исправить ваш код, также удалив существующий абзац, но именно в этот момент повторение кода становится очевидным, поскольку все функции (one, two и three) становятся невероятно похожими и повторяющиеся, кроме используемого текстового содержимого:

var readyGo = document.getElementById("readyGo");
var paragraph;

setTimeout(three,1000);

function three(){
    if( paragraph ){
      paragraph.remove();
    }
    paragraph = document.createElement("p");
    paragraph.textContent = "three"
    paragraph.className = "three nums";
    readyGo.appendChild(paragraph);
}

setTimeout(two, 2000);

function two(){
    if( paragraph ){
      paragraph.remove();
    }
    paragraph = document.createElement("p");
    paragraph.textContent = "two";
    paragraph.className = "two nums";
    readyGo.appendChild(paragraph);
}

setTimeout(one, 3000);

function one(){
    if( paragraph ){
      paragraph.remove();
    }
    paragraph = document.createElement("p");
    paragraph.textContent = "one";
    paragraph.className = "one nums";
    readyGo.appendChild(paragraph);
}
#readyGo {
    position:relative;
}

@-webkit-keyframes count {
    0% {transform: scale(1.5);}
    100% {transform: scale(1);}
}

.nums {
    font-size:5rem;
    height:auto;
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
    text-align:center;
}

.three {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}

.two {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}

.one {
    -webkit-animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
    animation:count 0.1s cubic-bezier(0.1,0.1,1,1) 1;
}
<div id="readyGo"></div>
...