我的程序使用鼠标移动来控制图形在屏幕上的位置,图形随着鼠标移动。这在 Chrome 和 IE 中按预期工作,但在 Firefox 中则不然。是否有一个 html 或 javascript 方法可以在所有三种浏览器中工作?
以下是在 Chrome 和 IE 中运行的代码步骤:(此处有完整的程序链接)http://www.midaslink.com/mastermind.htm
<body onMousemove=setup()>
<img id = "spot" name = "spot" src = "blank_dot.gif">
这会调用setup()
function setup()
{
mouseX = window.event.x;
mouseY = window.event.y;
window.status = mouseX + " " + mouseY;
this.document.all.spot.style.left = mouseX - 15;
this.document.all.spot.style.top = mouseY - 10;
}
在整个程序中,通过用户单击图形来更改点,这会将点 .src 更改为新图形,如下所示:
function green()
{
document.spot.src = "green_dot.gif"
}
function red()
{
document.spot.src = "red_dot.gif"
}
最佳答案
通常,浏览器差异会促使开发人员使用 jQuery 等框架来规范此类事情。
如果您不想走那条路,quirksmode.com 是一个很好的资源。这是您要查找的内容:http://www.quirksmode.org/js/events_properties.html#position
function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}
关于javascript - Firefox 使用鼠标 x,y 的方法与 Chrome 或 IE 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584663/