0

所以我试图用javascript编写一个像宝石一样的游戏,但不是点击一颗宝石然后点击另一颗宝石让他们切换位置,我想让玩家点击一颗宝石然后拖动到另一颗宝石让他们切换位置。在代码中,我使用变量 orb 作为珠宝。

function makeOrb(orb, x, y) {
    orb.className = "orb";
    var bejeweledarea = document.getElementById("bejeweledarea");
    bejeweledarea.appendChild(orb);
    var random = Math.round(Math.random() * (colors.length - 1));
    orb.style.backgroundColor = colors[random];
    orb.style.position = "absolute";
    orb.style.top = y + "px";
    orb.style.left = x + "px";
    orb.onmousedown = activate;
    if (activeSwitching) {
        orb.onmouseover = switchOrbs(activeOrb, orb);
    }
}

function activate() {
    activeSwitching = true;
    activeOrb = this;
}

function switchOrbs(orb, otherOrb) {
    var oldTop = orb.style.top;
    var oldLeft = orb.style.left;
    orb.style.top = otherOrb.style.top;
    orb.style.left = otherOrb.style.left;
    otherOrb.style.top = oldTop;
    otherOrb.style.left = oldLeft;
}

我可以将 activeSwitching 注册为 true,但由于某种原因,mouseover 事件无法正常工作。

4

1 回答 1

0

您现在正在向onmouseover刚刚单击的球体添加一个事件。我假设您希望所有其他球体都有一个onmouseover调用 的事件switchOrbs,对吗?因为您想在激活的球体悬停在另一个球体上时切换球体。

您可以将该鼠标悬停事件添加到所有球体。然后在该函数中检查 if activeSwitching = true。如果是这样,您执行例程进行切换。否则你停止,因为没有激活的球体并且程序需要等待orb.onmousedown/activate()调用。

编辑:代码大纲

$(".orbs").on("mouseover", function() {
  // `this` is the orb that is being hovered
  if( currentActiveOrb != null ) {
    switch(this, currentActiveOrb);
  }
}).on("mousedown", function() {
  // `this` is the orb that is being clicked
  currentActiveOrb = this;
}).on("mouseup", function() {
  currentActiveOrb = null;
});

function switch(hovered, active) {
  // Code to switch the orbs.
}
于 2013-11-15T07:41:45.017 回答