2016-03-03 43 views
1

我有一个自动唱首歌,随着鼠标的位置工作。这里是代码:使用JS代码鼠标的位置,并把位置在其他js代码

var elem = document.elementFromPoint(x,y); 

elem.addEventListener('click', function() { 
    console.log('clicked') 
}, false); 

var support = true; 

try { 
    if (new MouseEvent('click', {bubbles: false}).bubbles !== false) { 
     support = false; 
    } else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) { 
     support = false; 
    } 
} catch (e) { 
    support = false; 
} 

setInterval(function() { 
    if (support) { 
     var event = new MouseEvent('click'); 
    }else{ 
     var event = document.createEvent('Event'); 
     event.initEvent('click', true, true); 
    } 
    elem.dispatchEvent(event); 
},1000); 

,我也有获取鼠标位置代码:

var cursorX; 
var cursorY; 
document.onmousemove = function(e){ 
    cursorX = e.pageX; 
    cursorY = e.pageY; 
} 
setInterval("checkCursor()", 1000); 
function checkCursor(){ 
    alert(cursorX + ","+ cursorY); 
} 

,我的问题是:我怎么可以把鼠标位置在document.elementFromPoint(X,Y) ????

我知道能不能把我的X和Y,但我想x和y的更新,当我移动鼠标的任何地方

+0

的可能的复制[触发一个JavaScript点击()事件在特定的坐标(http://stackoverflow.com/questions/2845178/triggering-a-javascript-click-event-at-specific-coordinates) – Rayon

+0

我知道可以把我的X和Y,但我想X当我在任何地方移动鼠标时都会更新 –

回答

1

编辑

实际上,你需要初始化elemcursorXcursorY第一,对不起,没有测试这个代码。

申报ELEM作为变量 var elem = document.elementFromPoint(cursorX,cursorY);

和初始化光标cursorX = 0; cursorY = 0

那么你的鼠标移动函数中,做到这一点

document.onmousemove = function(e) { 
    cursorX = e.pageX; 
    cursorY = e.pageY; 
    elem = document.elementFromPoint(e.pageX, e.pageY); 
}