0

鼠标悬停效果应仅在特定画布位置创建。此外,我还创建了 MousePosition 函数(见下文)。鼠标悬停效果的命令应该在 MouseOverButton 函数上。

但它似乎仍然无法正常工作。

我的代码:

function init() {
    var can=document.getElementById("SnakeCanvas");
    var ctx=can.getContext("2d");
    can.addEventListener('mouseover',MouseOverButton, false);
}

function getPosition(event) {
    var x = new Number();
    var y = new Number();
    var can = document.getElementById("SnakeCanvas");

    if (event.x != undefined && event.y != undefined) {
        x = event.x;
        y = event.y;
    } else {//Firefox Compatability//
        x = event.clientX + document.body.scrollLeft +
        document.documentElement.scrollLeft;
        y = event.clientY + document.body.scrollTop +
        document.documentElement.scrollTop;
    }
    x -= can.offsetLeft;
    y -= can.offsetTop;
    return {mx:x, my:y};
}


function MouseOverButton(e) {
    var can=document.getElementById("SnakeCanvas");
    var ctx=can.getContext("2d");
    var cell=getPosition(event);

    if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
        ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
    }
}
4

2 回答 2

0

您的事件参数 infunction MouseOverButton(e)被调用e,但您event在将其传递给时使用getPosition

var cell=getPosition(event);应该var cell=getPosition(e);

于 2013-01-24T11:26:55.553 回答
0

尝试这个:

function MouseOverButton(e) {
    e = e || window.event; // Compatibility
    var can = document.getElementById("SnakeCanvas");
    var ctx = can.getContext("2d");
    var cell = getPosition(e);
//                         ^ That was `event`, breaking your code.
    if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
        ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
    }
}
于 2013-01-24T11:32:31.257 回答