Skip to main content
 首页 » 编程设计

javascript之同一元素上的单击和悬停事件发生冲突

2026年10月07日5jiqing9006

我有一个刷新“按钮”(实际上是一个 png 图像),用户可以将鼠标悬停在该按钮上,将其从灰色变为蓝色。单击刷新时,图像会变为播放“按钮”,该按钮表现出类似的颜色变化行为,只不过当您单击播放图像时,它应该切换回原始刷新图像。

问题是,点击刷新图像后,当我点击播放图像而不将鼠标从图像上移开时,它不会变回刷新图像。

我已经研究过事件传播停止。

这是我的代码:

$('#refresh').click(function (event) { 
    if (!tMinusZero) { 
        $('#refresh').html("<img src='play_small_hover.png'>"); 
        tMinusZero = true; 
        event.stopImmediatePropagation(); 
    } else { 
        $('#refresh').html("<img src='refresh_small_hover.png'>"); 
        tMinusZero = false;( 
        event.stopImmediatePropagation(); 
    } 
}); 
 
$('#refresh').hover(function () { 
    if (!tMinusZero) { 
        $('#refresh').html("<img src='refresh_small_hover.png'>"); 
    } else { 
        $('#refresh').html("<img src='play_small_hover.png'>"); 
    } 
}, function () { 
    if (!tMinusZero) { 
        $('#refresh').html("<img src='refresh_small.png'>"); 
    } else { 
        $('#refresh').html("<img src='play_small.png'>"); 
    } 
}); 

我在尝试调试时注意到一些有趣的事情:

  • 如果我将鼠标通过 #refresh 移动得太快,悬停将“粘住”,即隐式 mouseleave 将不会触发。
  • 注释掉悬停代码可修复点击问题。
  • 如果我在图像外部但在 div 内部单击,而不将鼠标从 div 上移开,则保留悬停代码,可以修复单击问题。
  • 在尝试再次单击之前将鼠标从 div 上移开可以解决单击问题。
  • 点击图像后,如果我将鼠标移到其上,它所更改的图像将在悬停图像和非悬停图像之间闪烁,但如果我首先将鼠标从 div 上移开,则不会闪烁。
  • 当我遇到点击问题时,有问题的图像会短暂闪烁,就好像切换到非悬停图像之一,然后快速变回有问题的图像。

在我看来,我的两个事件处理程序有利益冲突,但停止事件传播似乎没有帮助。

请您参考如下方法:

你为什么不尝试用CSS来解决你的问题,我认为它会更优雅,制作一个小DIV,背景与你的图像相对应,定义悬停状态和事件状态,再加上一个小脚本在另外 2 个状态之间进行更改

类似于: CSS:

#refresh[data-state=notclicked] 
{ 
background-image:url('play_small.png'); 
cursor:pointer; 
} 
#refresh[data-state=notclicked]:hover 
{ 
background-image:url('play_small_hover.png'); 
cursor:pointer; 
} 
#refresh[data-state=clicked] 
{ 
background-image:url('refresh_small.png'); 
cursor:pointer; 
} 
#refresh[data-state=clicked]:hover 
{ 
background-image:url('refresh_small_hover.png'); 
cursor:pointer; 
} 

当然,您必须在 CSS 中定义宽度和高度,以匹配您的 png 大小的固定 width.height。

比js:

$("#refresh").click(function(){ 
if ($(this).attr('data-state')=='clicked') {$(this).attr('data-state','notclicked');} 
else  {$(this).attr('data-state','clicked');} 
});