簡體   English   中英

Mouseover和mouseout不使用動畫元素觸發

[英]Mouseover and mouseout not firing with animating element

我需要檢測用戶是否將鼠標懸停在元素上,這很簡單。 但是,當元素動畫時,這些事件似乎不會觸發。 如果您查看我的小提琴,只需使該元素在鼠標上移動而不動鼠標,就可以看到事件不會觸發。 為何會發生這種情況很有意義,但是我一直找不到找到想要的行為的好方法,即使用戶不移動鼠標並且元素在其下設置動畫,也可以檢測到懸停。

有什么想法嗎?

謝謝!

注意:不使用外部庫的解決方案是最佳的,但是仍然可以提供任何幫助:)

的HTML

<div id='moving'></div>
<ul id="message"></ul>

的CSS

#moving {
  width: 50px;
  height: 50px;
  background-color: red;
  animation: move 7s linear;
}

@keyframes move {
    from {transform: translateX(0px)}
    to {transform: translateX(500px)}
}

JS

var counter = 0;

document.getElementById("moving").addEventListener("mouseover", function(){
    counter++;
    var node = document.createElement("LI");
    var textnode = document.createTextNode("Entered " + counter);
    node.appendChild(textnode);
    document.getElementById("message").appendChild(node);
});

document.getElementById("moving").addEventListener("mouseout", function(){
    var node = document.createElement("LI");
    var textnode = document.createTextNode("Left " + counter);
    node.appendChild(textnode);
    document.getElementById("message").appendChild(node);
});

這是一個小提琴: https : //jsfiddle.net/w5j842Lx/

您可以檢查鼠標是否在一定間隔內進出。 這是從您的小提琴延伸出來的工作小提琴。

 // This is the helper method I have written var addMoveListener = function(element, onmouseover, onmouseout) { var over = false; var mouseX, mouseY; var checkOver = function(ev) { if (ev) { mouseX = ev.clientX; mouseY = ev.clientY; } if (mouseX == null || mouseY == null) return; var rect = element.getBoundingClientRect(); var isInside = mouseX >= rect.left && mouseX < rect.right && mouseY >= rect.top && mouseY < rect.bottom; if (over && !isInside && onmouseout) onmouseout(); if (!over && isInside && onmouseover) onmouseover(); over = isInside; } document.addEventListener("mousemove", checkOver); var interval = setInterval(checkOver.bind(null, null), 100); } // Code below is for the sake of demonstration var counter = 0; var mouseovercallback = function() { counter++; console.log("Entered " + counter); }; var mouseoutcallback = function() { console.log("Left " + counter); }; addMoveListener(document.getElementById("moving"), mouseovercallback, mouseoutcallback); 
 #moving { width: 50px; height: 50px; background-color: red; animation: move 7s linear; } @keyframes move { from { transform: translateX(0px) } to { transform: translateX(500px) } } 
 <div id='moving'></div> 

該代碼檢查是否每隔100毫秒包含一次鼠標,以及是否移動了鼠標。 如果要處理元素不是矩形或被旋轉,傾斜等情況,則必須改進代碼。

看看這個jsfiddle https://jsfiddle.net/3vpaoj59/,它包含一個類似這樣的函數

  setInterval(checkMouse, 100);

基本上每秒調用一次函數10次,以檢查鼠標的坐標是否在動畫形狀內。 您的形狀是正方形而不是圓形,因此您必須做一些不同的數學運算。 這段代碼很不錯,因為它不使用插件,但是可能會占用大量CPU,並且在某些情況下可能會降低性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM