一叠纸牌效果:拖动时将zIndex更改为所有类似div中的最大值

问题描述

我尝试在开始拖动时使用z-index在所有类似的div上放置一个div。我的尝试有点奏效,但是当单击3的另一个div时,那个不在顶部而是停留在下面。

// Handle start moving
const handleMoveStart = () => {
    const currentIndex = parseInt(document.defaultview.getComputedStyle(card).getPropertyValue('z-index'))
    const popupsAmount = document.querySelectorAll('.playingcard').length
    index = currentIndex + popupsAmount + 1
}

GIF可能更清晰:

enter image description here

无论我有多少,如何在拖动时始终将div放在“桩”的顶部?

解决方法

该问题似乎只是在增加z-index。如果您多次单击一张卡,则必须单击相同次数的其他卡才能赶上它们。 在三张纸牌的示例中,我会朝相反的方向进行操作,并且将所有纸牌0-2的z索引从3种状态之一开始。用唯一的编号初始化所有三张纸牌的z-index,并在单击某张纸牌时将其设为z -index = 2,其他值减为0。

编辑:之所以尝试这样做,是因为我自己在工作时遇到了类似的z-index问题,因此我不得不花很多时间来弄清楚我的问题。除此以外,我还不够聪明,无法对其进行完善: https://jsfiddle.net/damussel06/gkso24va/168/

const cardZero = document.getElementById("cardZero");
const cardOne = document.getElementById("cardOne");
const cardTwo = document.getElementById("cardTwo");


$(document).ready(function() {

  // z-index initalize  
  cardZero.style.zIndex = 1;
  cardZero.innerHTML = cardZero.style.zIndex;

  cardOne.style.zIndex = 2;
  cardOne.innerHTML = cardOne.style.zIndex;

  cardTwo.style.zIndex = 3;
  cardTwo.innerHTML = cardTwo.style.zIndex;
})



function cardOnTop(c) {

  /* clicked card gets z=index of 3 */
  topCard = document.getElementById(c);

  /* if top card is already on top do nothing */
  if (topCard.style.zIndex != 3) {

    /* set cards */
    switch (c) {
      case 'cardZero':
        // fix cards one and two
        if (cardZero.style.zIndex == 1) {
          cardOne.style.zIndex--;
          cardTwo.style.zIndex--;
        } else {
          cardOne.style.zIndex = 1;
          cardTwo.style.zIndex = 2;
        }
        // set picked cardZero
        cardZero.style.zIndex = 3;
        break;

      case 'cardOne':
        // fix cards zero and two
        if (cardOne.style.zIndex == 1) {
          cardZero.style.zIndex--;
          cardTwo.style.zIndex--;
        } else {
          cardZero.style.zIndex = 1;
          cardTwo.style.zIndex = 2;
        }
        // set picked cardOne
        cardOne.style.zIndex = 3;
        break;

      case 'cardTwo':
        // fix cards zero and one
        if (cardTwo.style.zIndex == 1) {
          cardZero.style.zIndex--;
          cardOne.style.zIndex--;
        } else {
          cardZero.style.zIndex = 1;
          cardOne.style.zIndex = 2;
        }
        // set picked cardTwo
        cardTwo.style.zIndex = 3;
        break;

      default:
        cardTable.innerHTML = 'error !';
    }


    /* displays new style.z-index on card */
    cardZero.innerHTML = cardZero.style.zIndex;
    cardOne.innerHTML = cardOne.style.zIndex;
    cardTwo.innerHTML = cardTwo.style.zIndex;
  }

}