根据存储在数组中的序列更改元素的外观

时间:2016-05-22 02:57:57

标签: javascript

我在两个span标签中有两个四分之一的圆圈:

<div>
  <span id="topleft"></span>
  <span id="topright"></span>
</div>

<button id = 'clickme' style = 'margin-top: 100px;'>CLICK ME</button>

当我点击按钮时,我希望div能够点亮&#39;基于使用JavaScript存储在数组中的序列:

let reset = (position) => { 
  document.getElementById(position).style.opacity = 1; 
};

let blink = (position) => {
  document.getElementById(position).style.opacity = 0.5;
};

let sequence = (positions) => {

  let currentBlink = positions.pop();
  blink(currentBlink);
  setTimeout(reset.bind(null, currentBlink), 1000);

  if (positions.length > 0) {
    sequence(positions);
  }

}

document.getElementById('clickme').onclick = () => {
  sequence(positions);
}

let positions = ['topleft', 'topright'];

问题是两个div都会点亮&#39;与此同时,我实际上想要在两者之间暂停。

我怎样才能达到这个效果?

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

在回调中timeout之后调用该函数。

&#13;
&#13;
let reset = (position) => {
  document.getElementById(position).style.opacity = 1;
};

let blink = (position) => {
  document.getElementById(position).style.opacity = 0.5;
};

let sequence = (positions) => {
  let currentBlink = positions.pop();
  blink(currentBlink);
  setTimeout(function() {

    reset(currentBlink);
    if (positions.length > 0) {
      sequence(positions);
    }
  }, 1000);
}

document.getElementById('clickme').onclick = () => {
  sequence(positions);
}

let positions = ['topleft', 'topright'];
&#13;
<div>
  <span id="topleft">aaa</span>
  <span id="topright">aaa</span>
</div>
<button id='clickme' style='margin-top: 100px;'>CLICK ME</button>
&#13;
&#13;
&#13;

Fiddle Demo