[英]Conflicting click and hover events on the same element
我有一个刷新“按钮”(实际上是一个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'>");
}
});
在尝试调试时我注意到一些有趣的事情:
在我看来,我的两个事件处理程序有利益冲突,但停止事件传播似乎没有帮助。
如果我正确理解你希望它如何表现,你的代码似乎工作正常,即使在click事件中有一个拼写错误(圆括号)。
tMinusZero = false;(
此外,只是为了改进您可以替换的代码
$('#refresh')
同
$(this)
在事件内部,因为它将引用您附加事件的dom元素。
你为什么不尝试用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');}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.