admin管理员组

文章数量:1287162

I have this bit of js that basically creates a slot machine effect. It rotates between 1-12 and stops on one of them randomly. Works perfectly fine. but I would PREFER to change these to images but I've struggled to figure that out. Any help?

I did try simply inserting html in the place and it just displays the text. I'm not at all good at writing/editing jscript.

CodePen Link:

(function () {
  const items = [
    '1',
    '2',
    '3',    
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
  ];
  const doors = document.querySelectorAll('.door');
  
  document.querySelector('#spinner').addEventListener('click', spin);
  document.querySelector('#reseter').addEventListener('click', init);

  function init(firstInit = true, groups = 1, duration = 1) {
    for (const door of doors) {
      if (firstInit) {
        door.dataset.spinned = '0';
      } else if (door.dataset.spinned === '1') {
        return;
      }

      const boxes = door.querySelector('.boxes');
      const boxesClone = boxes.cloneNode(false);
      const pool = ['❓'];

      if (!firstInit) {
        const arr = [];
        for (let n = 0; n < (groups > 0 ? groups : 1); n++) {
          arr.push(...items);
        }
        pool.push(...shuffle(arr));

        boxesClone.addEventListener(
          'transitionstart',
          function () {
            door.dataset.spinned = '1';
            this.querySelectorAll('.box').forEach((box) => {
              box.style.filter = 'blur(1px)';
            });
          },
          { once: true }
        );

        boxesClone.addEventListener(
          'transitionend',
          function () {
            this.querySelectorAll('.box').forEach((box, index) => {
              box.style.filter = 'blur(0)';
              if (index > 0) this.removeChild(box);
            });
          },
          { once: true }
        );
      }

      for (let i = pool.length - 1; i >= 0; i--) {
        const box = document.createElement('div');
        box.classList.add('box');
        box.style.width = door.clientWidth + 'px';
        box.style.height = door.clientHeight + 'px';
        box.textContent = pool[i];
        boxesClone.appendChild(box);
      }
      boxesClone.style.transitionDuration = `${duration > 0 ? duration : 1}s`;
      boxesClone.style.transform = `translateY(-${door.clientHeight * (pool.length - 1)}px)`;
      door.replaceChild(boxesClone, boxes);
    }
  }

  async function spin() {
    init(false, 1, 2);
    
    for (const door of doors) {
      const boxes = door.querySelector('.boxes');
      const duration = parseInt(boxes.style.transitionDuration);
      boxes.style.transform = 'translateY(0)';
      await new Promise((resolve) => setTimeout(resolve, duration * 100));
    }
  }

  function shuffle([...arr]) {
    let m = arr.length;
    while (m) {
      const i = Math.floor(Math.random() * m--);
      [arr[m], arr[i]] = [arr[i], arr[m]];
    }
    return arr;
  }

  init();
})();

I have this bit of js that basically creates a slot machine effect. It rotates between 1-12 and stops on one of them randomly. Works perfectly fine. but I would PREFER to change these to images but I've struggled to figure that out. Any help?

I did try simply inserting html in the place and it just displays the text. I'm not at all good at writing/editing jscript.

CodePen Link: https://codepen.io/DrChickles/pen/yyLJEGe

(function () {
  const items = [
    '1',
    '2',
    '3',    
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
  ];
  const doors = document.querySelectorAll('.door');
  
  document.querySelector('#spinner').addEventListener('click', spin);
  document.querySelector('#reseter').addEventListener('click', init);

  function init(firstInit = true, groups = 1, duration = 1) {
    for (const door of doors) {
      if (firstInit) {
        door.dataset.spinned = '0';
      } else if (door.dataset.spinned === '1') {
        return;
      }

      const boxes = door.querySelector('.boxes');
      const boxesClone = boxes.cloneNode(false);
      const pool = ['❓'];

      if (!firstInit) {
        const arr = [];
        for (let n = 0; n < (groups > 0 ? groups : 1); n++) {
          arr.push(...items);
        }
        pool.push(...shuffle(arr));

        boxesClone.addEventListener(
          'transitionstart',
          function () {
            door.dataset.spinned = '1';
            this.querySelectorAll('.box').forEach((box) => {
              box.style.filter = 'blur(1px)';
            });
          },
          { once: true }
        );

        boxesClone.addEventListener(
          'transitionend',
          function () {
            this.querySelectorAll('.box').forEach((box, index) => {
              box.style.filter = 'blur(0)';
              if (index > 0) this.removeChild(box);
            });
          },
          { once: true }
        );
      }

      for (let i = pool.length - 1; i >= 0; i--) {
        const box = document.createElement('div');
        box.classList.add('box');
        box.style.width = door.clientWidth + 'px';
        box.style.height = door.clientHeight + 'px';
        box.textContent = pool[i];
        boxesClone.appendChild(box);
      }
      boxesClone.style.transitionDuration = `${duration > 0 ? duration : 1}s`;
      boxesClone.style.transform = `translateY(-${door.clientHeight * (pool.length - 1)}px)`;
      door.replaceChild(boxesClone, boxes);
    }
  }

  async function spin() {
    init(false, 1, 2);
    
    for (const door of doors) {
      const boxes = door.querySelector('.boxes');
      const duration = parseInt(boxes.style.transitionDuration);
      boxes.style.transform = 'translateY(0)';
      await new Promise((resolve) => setTimeout(resolve, duration * 100));
    }
  }

  function shuffle([...arr]) {
    let m = arr.length;
    while (m) {
      const i = Math.floor(Math.random() * m--);
      [arr[m], arr[i]] = [arr[i], arr[m]];
    }
    return arr;
  }

  init();
})();
Share Improve this question edited Feb 28 at 4:34 OverSamu 16211 bronze badges asked Feb 23 at 18:48 Doctor ChicklesDoctor Chickles 112 bronze badges 11
  • Manually entering numbers from 1 to 12 in the code? No answer can help you, sorry. – Sergey A Kryukov Commented Feb 23 at 18:52
  • That's not what I'm asking. Right now it calls to whatever next is in those spaces. I thought maybe there was a way to load an images in their places. – Doctor Chickles Commented Feb 23 at 20:19
  • I know that's not what you are asking. I'm just saying that it would be too hard to waste time on your question after seeing this. I am sorry to say so, but this is what it is. Honestly. If you comb your code to some acceptable level, it will be a different story. – Sergey A Kryukov Commented Feb 23 at 21:01
  • click edit then click the button shaped like this [<>] and provide a minimal reproducible example with a description of what you want the code to do and what it does not do or does instead – mplungjan Commented Feb 23 at 21:47
  • Why the jscript tag? – Barmar Commented Feb 23 at 22:28
 |  Show 6 more comments

1 Answer 1

Reset to default 0

Instead of writing numbers in .box elements, simply append your images to them.

const box = document.createElement('div');
box.classList.add('box');
const { clientWidth: w, clientHeight: h } = door;
box.style.width = `${w}px`;
box.style.height = `${h}px`;
const img = document.createElement('img');
img.src = `https://placehold.co/${w}x${h}?text=${pool[i]}`
box.appendChild(img);
boxesClone.appendChild(box);

Here are the changes applied to the code in your CodePen:

(function() {
  const items = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
  ];
  const doors = document.querySelectorAll('.door');

  document.querySelector('#spinner').addEventListener('click', spin);
  document.querySelector('#reseter').addEventListener('click', init);

  function init(firstInit = true, groups = 1, duration = 1) {
    for (const door of doors) {
      if (firstInit) {
        door.dataset.spinned = '0';
      } else if (door.dataset.spinned === '1') {
        return;
      }

      const boxes = door.querySelector('.boxes');
      const boxesClone = boxes.cloneNode(false);
      const pool = ['❓'];

      if (!firstInit) {
        const arr = [];
        for (let n = 0; n < (groups > 0 ? groups : 1); n++) {
          arr.push(...items);
        }
        pool.push(...shuffle(arr));

        boxesClone.addEventListener(
          'transitionstart',
          function() {
            door.dataset.spinned = '1';
            this.querySelectorAll('.box').forEach((box) => {
              box.style.filter = 'blur(1px)';
            });
          }, {
            once: true
          }
        );

        boxesClone.addEventListener(
          'transitionend',
          function() {
            this.querySelectorAll('.box').forEach((box, index) => {
              box.style.filter = 'blur(0)';
              if (index > 0) this.removeChild(box);
            });
          }, {
            once: true
          }
        );
      }

      for (let i = pool.length - 1; i >= 0; i--) {
        const box = document.createElement('div');
        box.classList.add('box');
        const {
          clientWidth: w,
          clientHeight: h
        } = door;
        box.style.width = `${w}px`;
        box.style.height = `${h}px`;
        const img = document.createElement('img');
        img.src = `https://placehold.co/${w}x${h}?text=${pool[i]}`
        box.appendChild(img);
        boxesClone.appendChild(box);
      }
      boxesClone.style.transitionDuration = `${duration > 0 ? duration : 1}s`;
      boxesClone.style.transform = `translateY(-${door.clientHeight * (pool.length - 1)}px)`;
      door.replaceChild(boxesClone, boxes);
    }
  }

  async function spin() {
    init(false, 1, 2);

    for (const door of doors) {
      const boxes = door.querySelector('.boxes');
      const duration = parseInt(boxes.style.transitionDuration);
      boxes.style.transform = 'translateY(0)';
      await new Promise((resolve) => setTimeout(resolve, duration * 100));
    }
  }

  function shuffle([...arr]) {
    let m = arr.length;
    while (m) {
      const i = Math.floor(Math.random() * m--);
      [arr[m], arr[i]] = [arr[i], arr[m]];
    }
    return arr;
  }

  init();
})();
body {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
}

#app {
  width: 100%;
  height: 100%;
  background: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.doors {
  display: flex;
}

.door {
  background: #fafafa;
  width: 360px;
  height: 300px;
  overflow: hidden;
  border-radius: 5px;
  margin: 5px;
}

.boxes {
  /* transform: translateY(0); */
  transition: transform 1s ease-in-out;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 3rem;
}

.buttons {
  margin: 1rem 0 2rem 0;
}

button {
  cursor: pointer;
  font-size: 1.2rem;
  margin: 0 0.2rem;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
}

.info {
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
}

.nodisplay {
  display: none;
}
<div id="app">
  <div class="doors">
    <div class="door nodisplay">
      <div class="boxes">
        <!-- <div class="box">?</div> -->
      </div>
    </div>

    <div class="door">
      <div class="boxes">
        <!-- <div class="box">?</div> -->
      </div>
    </div>

    <div class="door nodisplay">
      <div class="boxes">
        <!-- <div class="box">?</div> -->
      </div>
    </div>
  </div>

  <div class="buttons">
    <button id="spinner">Play</button>
    <button id="reseter">Reset</button>
  </div>
</div>

本文标签: javascriptHow to replace text elements with imagesStack Overflow