最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if statement - How to start over when a certain condition is met? - Stack Overflow

programmeradmin0浏览0评论

I'm writing a program which I want it to start over, that is, reset to initial value and continue when a certain condition is met. But when the condition is met, the program does not reset to the initial value immediately and start over after two extra steps.

<div>
      <div class="box red"></div>
      <div class="box green"></div>
    </div>
const box = document.querySelector('.box');
const r = 60;
const g = 60;
const b = 60;
let a = 0.1;
let count = 0;
box.addEventListener('mouseover', () => {
  if (count <= 10) {
    box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;
    count++;
    a += 0.1;
  } else {
    count = 0;
    a = 0.1;
  }

  console.log(count);
});

Program output screenshot

In the image above, I have shown the current output. My condition is fully met at 10, and then I want it to start from 1 again as count and 0.1 as a(opacity), but I am getting 11 and 0 respectively as count when the opacity is not changing before getting to count 1 again and opacity in motion.

I tried using count = 1, but no avail. What have I done wrong here?

I'm writing a program which I want it to start over, that is, reset to initial value and continue when a certain condition is met. But when the condition is met, the program does not reset to the initial value immediately and start over after two extra steps.

<div>
      <div class="box red"></div>
      <div class="box green"></div>
    </div>
const box = document.querySelector('.box');
const r = 60;
const g = 60;
const b = 60;
let a = 0.1;
let count = 0;
box.addEventListener('mouseover', () => {
  if (count <= 10) {
    box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;
    count++;
    a += 0.1;
  } else {
    count = 0;
    a = 0.1;
  }

  console.log(count);
});

Program output screenshot

In the image above, I have shown the current output. My condition is fully met at 10, and then I want it to start from 1 again as count and 0.1 as a(opacity), but I am getting 11 and 0 respectively as count when the opacity is not changing before getting to count 1 again and opacity in motion.

I tried using count = 1, but no avail. What have I done wrong here?

Share Improve this question asked Mar 12 at 8:58 Mahadi Hasan SumonMahadi Hasan Sumon 31 bronze badge 0
Add a comment  | 

1 Answer 1

Reset to default 0

You are logging the counter after increasing/resetting it.

Try something like this:

let a = 0.1;
let count = 0;
box.addEventListener('mouseover', () => {
  if (count == 10) {
    count = 0;
    a = 0.1;
  }
  console.log(count);
  box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;
  count++;
  a += 0.1;
});
发布评论

评论列表(0)

  1. 暂无评论