在同一元素上发生冲突的点击和悬停事件

时间:2014-02-16 08:32:03

标签: javascript jquery

我有一个刷新“按钮”(实际上是一个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太快,则悬停将“粘住”,即隐式鼠标距离不会触发。
  • 注释掉悬停代码可以解决点击问题。
  • 留下悬停代码,如果我点击图片外部但在div内部,而不从div中删除我的鼠标,修复了点击问题。
  • 在尝试再次单击之前从div中删除鼠标可以解决单击问题。
  • 点击图片后,如果我将鼠标移到鼠标悬停图像上,那么它更改为的图像会在悬停图像和非悬停图像之间闪烁,但如果我先从div中删除鼠标则不会闪烁。
  • 当我遇到点击问题时,有问题的图像会瞬间闪烁,就像切换到其中一个非悬停图像一样,然后快速变回有问题的图像。

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

2 个答案:

答案 0 :(得分:0)

如果我理解你的行为方式,你的代码似乎工作得很好,即使在点击事件(圆括号)中有拼写错误。

tMinusZero = false;(

另外,只是为了改进你可以替换的代码

$('#refresh') 

$(this)

在事件内部,因为它将引用您将事件附加到的dom元素。

答案 1 :(得分:0)

为什么不试着用CSS来解决你的问题,我认为它会更优雅,制作一个小DIV,背景与你的图像相对应,定义悬停状态和活动状态,再加上一个小脚本更改另外两个州

像: 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');}
});
相关问题