0

为简单起见,以下 javascript 和 css 在 Chrome 和 Firefox 中运行良好。一旦我在 IE 中对其进行了测试,在我触发了与鼠标位置相关的任何代码(例如更改鼠标指针)后,Y 值就会变得非常糟糕。它增加了90个像素或几乎翻倍等。代码和样式如下:

<style>
    #miContenedor{
        width:780px;
        height:1600px;
        margin:auto;
        margin-top:185px;
        position:relative;
        border: 4px solid black;
    }
    #miCanvas{
        background-image:url(Images/mat06pag34.png);
        background-repeat:no-repeat;
    }
</style>
<script>
canvas.addEventListener('click',ProcessClick,false);
function ProcessClick(toi){
    var posx = toi.layerX;
    var posy = toi.layerY;
    if(toi.layerX == undefined || toi.layerY == undefined){
        posx = toi.offsetX;
        posy = toi.offsetY;
    }
}//ProcessClick

canvas.onmousemove = function(tamos){
    var posxX = tamos.layerX;
    var posyY = tamos.layerY;
    if(tamos.layerX == undefined || tamos.layerY == undefined){
        posxX = tamos.offsetX;
        posyY = tamos.offsetY;
    }
    var coords = posxX + "," + posyY; ctx.clearRect(700, 300, 80, 40); ctx.fillText(coords, 700, 320);
    if(posxX>=30 && posxX<=420 && posyY>=380 && posyY<=400){
        canvas.style.cursor = "help";
    }
    else{
        canvas.style.cursor = "default";
    }
}//onmousemove
</script>
4

1 回答 1

0

发现是页面的滚动弄乱了我的坐标。尝试了scrollLeftscrollTop但最终找到了一个更简单的解决方案:首先尝试 offsetX / offsetY,然后是 layerX / layerY。

canvas.addEventListener('click',ProcessClick,false);
function ProcessClick(toi){
    var posx = toi.offsetX;
    var posy = toi.offsetY;
    if(toi.offsetX == undefined || toi.offsetY == undefined){
        posx = toi.layerX;
        posy = toi.layerY;
    }
    var coord = "Click en: " + posx + "," + posy;
    if(posx>=100 && posx<=200 && posy>=100 && posy<=200){
        ctx.clearRect(250, 235, 500, 30);
        ctx.fillText(coord, 250, 250);
    }
}//ProcessClick

canvas.onmousemove = function(tamos){
    var posxX = tamos.offsetX;
    var posyY = tamos.offsetY;
    if(tamos.offsetX == undefined || tamos.offsetY == undefined){
        posxX = tamos.layerX;
        posyY = tamos.layerY;
    }
    var coords = posxX + "," + posyY; ctx.clearRect(250, 335, 500, 30); ctx.fillText(coords, 250, 350);
    if(posxX>=100 && posxX<=200 && posyY>=100 && posyY<=200){
        canvas.style.cursor = "pointer";
    }
    else{
        canvas.style.cursor = "default";
    }
}//onmousemove
于 2013-01-19T22:46:49.143 回答