Как остановить движение вправо при наведении мыши и разрешить запуск возврата в текущем месте? - PullRequest
0 голосов
/ 24 апреля 2018
// set up array to contain custom classes of each block element
let blockClsList = [];
// custom block classes pushed into blockClsList array
for (let i = 0; i < document.getElementsByClassName('blocks') 
    [0].children.length; i++) {
    blockClsList.push(document.getElementsByClassName('blocks') 
    [0].children[i].classList[1]);
};

// ======================  Travelers  =========================

const moveRight = (event) => {
    let marginPX = 10;

Здесь я установил Интервал для анимации. Я прочитал документацию MDN, и я все еще не уверен, что устанавливаю это на правильный элемент. Нужно ли прикреплять setInterval к ​​классу бокса?

    window.setInterval(function () {
    // when margin is smaller than 300
        if (marginPX < 300) {
            marginPX++;
            event.target.style.marginLeft = marginPX + 'px';
        }
    }, 5);
};

// sets event listeners for mousedown on all blocks
for (let i = 0; i < blockClsList.length; i++) {
    document.querySelector('.' + 
    blockClsList[i]).addEventListener('mousedown', moveRight);
};

const moveBack = (event) => {

Здесь я очищаю интервал, чтобы начать moveBack в текущем местоположении, но Это не работает. Обе анимации пытаются выполнить одновременно.

Должен ли я использовать startanimation и остановить анимацию? Если так, то как бы это выглядело. Я также пытался переместить clearInterval, но мне это не удалось.

    window.clearInterval(moveRight);
    let marginPX = 300;
    window.setInterval(function () {
        if (marginPX > 10) {
            marginPX--;
            event.target.style.marginLeft = marginPX + 'px';
        }
    }, 5);
};

// sets event listeners for mouseup on all blocks
for (let i = 0; i < blockClsList.length; i++) {
    document.querySelector('.' + 
    blockClsList[i]).addEventListener('mouseup', moveBack);
};

1 Ответ

0 голосов
/ 25 апреля 2018

body {
  display: flex;
  /*justify-content: center;*/
}

.blocks {
  margin-top: 5%;
  display: flex;
  flex-direction: column;
}

.block {
  width: 100px;
  height: 100px;
  margin: 10px;
}

.block--red {
  background-color: red;
}

.block--blue {
  background-color: blue;
}

.block--green {
  background-color: green;
}

.block--pink {
  background-color: pink;
}

.block--gray {
  background-color: gray;
}
<html>

<head>
  <title>DOM II</title>
</head>

<body>
  <div class="blocks">
    <div class="block block--red"></div>
    <div class="block block--blue"></div>
    <div class="block block--green"></div>
    <div class="block block--pink"></div>
    <div class="block block--gray"></div>
  </div>
  <script>
    // set up array to contain custom classes of each block element
    let blockClsList = [];
    // custom block classes pushed into blockClsList array
    for (let i = 0; i < document.getElementsByClassName('blocks') 
[0].children.length; i++) {
      blockClsList.push(document.getElementsByClassName('blocks')[0].children[i].classList[1]);
    };

    // ==================  Travelers  ======================
    let marginPX = {};
    let inter = {};

    const moveRight = (event) => {
      
window.clearInterval(inter[`${event.target.attributes[0].nodeValue}`]);
      inter[`${event.target.attributes[0].nodeValue}`] = setInterval(function() {
        // when margin is smaller than 300
        if (marginPX[`${event.target.attributes[0].nodeValue}`] === undefined) {
          marginPX[`${event.target.attributes[0].nodeValue}`] = 10;
        }
        if (marginPX[`${event.target.attributes[0].nodeValue}`] < 300) {
          marginPX[`${event.target.attributes[0].nodeValue}`]++;
          event.target.style.marginLeft = marginPX[`${event.target.attributes[0].nodeValue}`] + 'px';
        }
      }, 5);
    }

    // sets event listeners for mousedown on all blocks
    for (let i = 0; i < blockClsList.length; i++) {
      document.querySelector('.' + blockClsList[i]).addEventListener('mousedown', moveRight);
    }

    const moveBack = (event) => {
      window.clearInterval(inter[`${event.target.attributes[0].nodeValue}`]);
      inter[`${event.target.attributes[0].nodeValue}`] = setInterval(function() {
        clearInterval(moveRight);
        if (marginPX[`${event.target.attributes[0].nodeValue}`] > 10) {
          marginPX[`${event.target.attributes[0].nodeValue}`]--;
          event.target.style.marginLeft = marginPX[`${event.target.attributes[0].nodeValue}`] + 'px';
        }
      }, 5);
    }

    // sets event listeners for mouseup on all blocks
    for (let i = 0; i < blockClsList.length; i++) {
      document.querySelector('.' + blockClsList[i]).addEventListener('mouseup', moveBack);
    }
  </script>
</body>

</html>
...