[英]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.