2016-12-03 36 views
0

我有一个divonmousemove,我用来使对象跟随光标。在这div我有另一divonmouseleave。问题在于,onmouseleave只有在将光标从对象中快速移出时才起作用。但是,如果我删除onmousemoveonmouseleave开始正常工作。我怎样才能让onmousemoveonmouseleave同时工作?onmouseleave不会在onmousemove内工作

的HTML:

<body> 
    <div onmousemove="cursorMove(event)" id="main"> 
     <p id="title">...</p> 
     <div onmouseleave="gameOver()" id="light"></div> 
     <div id="cursor"></div> 
    </div> 
    <button onclick="moveLight()">move</button> 
    <button onclick="startGame()">start</button> 
    <script src="js/javascript.js"></script> 
</body> 

中的JavaScript

function cursorMove(event) { 
    document.getElementById("cursor").style.top = event.clientY - 14; 
    document.getElementById("cursor").style.left = event.clientX - 14; 
    document.getElementById("cursor").style.opacity = '1'; 
} 
function gameOver() { 
    console.log("Game Over"); 
    document.getElementById("light").style.top = 245 + 'px'; 
    document.getElementById("light").style.left = 238 + 'px'; 
    document.getElementById("title").style.opacity = '1'; 
    document.getElementById("title").innerHTML = 'Enter the light'; 
    gameActive = false; 
} 

回答

0

尝试里面:onmousemove。两者的功能是在mousemove

function cursorMove(event) { 
    document.getElementById("light").onmouseleave(); 
} 

的时间运行
<div onmousemove="cursorMove(event),gameOver()" id="main"> 
0

我不知道你的整个脚本代码,但我认为你试图从非全局上下文中调用函数cursorMovegameOver。您正在使用内联事件处理程序,并且您的函数必须位于窗口执行上下文中。

尝试不同的方法。例如:https://jsfiddle.net/4hkkm7k5/

此外,内联事件处理程序可能不是一个好主意。请参阅:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don't_use_these

+0

我试图用addEventListner替换内联事件,但不幸的是它没有任何区别。 –

+0

我修改了一下例子:https://jsfiddle.net/4hkkm7k5/1/ –