拖动div元素,然后用另一个元素切换位置

时间:2013-11-15 07:14:54

标签: javascript

所以我试图在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事件无法正常工作。

1 个答案:

答案 0 :(得分:0)

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

您可以将鼠标悬停事件添加到所有球体。在该功能中,您可以检查是否activeSwitching = true。如果是,则执行例程切换。否则你会停止,因为没有激活的orb,程序需要等待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.
}