2017-06-04 70 views
1

我想更改div的innerHTML與onmousemove事件。更改innerHTML onmousemove事件

假設當鼠標移過div時,innerHTML更改爲「鼠標正在移動」。當鼠標停止移動時,它會返回默認的innerHTML值:「鼠標不移動」。

很簡單。我知道有你可以用它來撤消OnMouseEnter在的onmouseover行動OnMouseLeave在事件,但沒有「onmousecalm」事件撤消的OnMouseMove

如何實現?

+0

請張貼您的代碼 –

回答

1

你可以使用mousemove設置innerHTML每一次事件觸發時,得到一個時間戳然後用setInterval帶有某種閾值,當鼠標停止檢測移動重置innerHTML

var div = document.querySelector('div'), 
 
    move = div.getAttribute('data-move'), 
 
    pause = div.innerHTML, 
 
    threshold = 500; 
 

 
div.addEventListener('mousemove',function() { 
 
    lastMoved = new Date().getTime(); 
 
    div.innerHTML = move; 
 
    var timeout = setTimeout(function() { 
 
    var nowTime = new Date().getTime(); 
 
    if (nowTime - lastMoved > threshold) { 
 
     div.innerHTML = pause; 
 
    } 
 
    }, threshold) 
 
});
div { 
 
    padding: 5em; 
 
    border: 1px solid black; 
 
}
<div data-move="mouse is moving">mouse is not moving</div>