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