2013-11-15 58 views
0

所以我试图编写一个像JavaScript的珠宝类游戏,但不是点击一个宝石,然后点击另一个宝石,让他们切换位置,我希望玩家点击一颗宝石然后拖到另一颗宝石上,让它们转换位置。在代码中,我使用变量orb作为宝石。拖动div元素,然后用另一个元素切换位置

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事件无法正常工作。

回答

0

您现在将一个onmouseover事件添加到刚被点击的圆球。我想你想要所有的其他球体有onmouseover事件,调用switchOrbs,对吧?因为当激活的物体悬停在另一个球体上时,你想切换球体。

您可以将该鼠标悬停事件添加到全部该球体。在那个函数中,你检查是否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. 
} 
+0

是的,你是对的。我想让其他球体拥有onmouseover事件。我如何着手将事件添加到所有球体?你能再详细一点吗? – user2995240

+0

我添加了一个伪大纲。 – Roemer

+0

非常感谢帮助! – user2995240

相关问题