2013-10-16 107 views
0

1)當#pin_point是上懸停,我設置兩個絕對定位圖像以fadeToggle使得它與淡入淡出效果的變化:結合和非結合功能

$("#pin_point").hover(function hoverhandler() { 
    $("#pin_point img").fadeToggle('medium'); 
}); 

2)當#pin_point被點擊時,我設置pin_point img交換到 「ex.png」:

$("#pin_point").click(function() { 
    $("#pin_point img").attr('src','images/ex.png'); 
}); 

3)當點擊#pin_point我也解除綁定在#1(上文)懸停功能。

問題:如果我想再次點擊#pin_point時綁定函數, 我該怎麼辦?下面是我的代碼,我很難搞清楚。 任何人都可以幫忙嗎?

$("#pin_point").click(function() { 
    $('#pin_point').unbind('hover', hoverhandler); 
    $("#pin_point img").attr('src','images/ex.png'); 
    $('#pin_point').bind('hover', hoverhandler); 
}); 
+0

你能解釋一下你想要發生什麼,以及如何解決你的特定問題? – dclowd9901

+0

你能告訴你到底想要做什麼嗎? –

+0

當#pin_point再次點擊時,我試圖展示#pin_point img而不是'image/ex.png'。夠清楚了嗎? –

回答

0

hover是一個簡短的事件。取而代之的是取消綁定mousentermouseleave。還將狀態信息附加到元素以獲得每次點擊的替代效果。

function hoverhandler() { 
    $("img", this).stop(true, true).fadeToggle('medium'); 
} 
$("#pin_point").hover(hoverhandler); 

$("#pin_point").click(function() { 
    var $this = $(this), 
     enableHover = $this.data('enableHover'), //get the current state 
     method = "bind"; //default mathod to bind 

    if (!enableHover) { //if alternate click to disable 
     method = "unbind"; //change the method 
    } 

    $this[method]('mouseenter mouseleave', hoverhandler); //apply the method 
    $this.find("img").prop('src', 'http://placehold.it/40x40'); 
    $this.data('enableHover', !enableHover);//save the state in the element to toggle between each click 

}); 

你可以,如果你正在使用jQuery版本> = 1.7使用onoff

Demo

+0

當div再次被點擊時,它不會變回50X50。相反,它會更改爲40X40,這是來自src的img屬性。你能告訴我如何解決這個問題嗎? –

+0

@KcLee你可以添加該部分切換在其他部分的圖像...看到這個http://jsfiddle.net/T3ct5/ – PSL

+0

@KcLee這就是你要求的? – PSL

0

什麼你傳遞給.hovernamed function expression。它的名字是不應該提供給其他的代碼,你要使它成爲一個函數聲明:

function hoverhandler() { 
    $("#pin_point img").fadeToggle('medium'); 
} 
$("#pin_point").hover(hoverhandler); 

據jQuery的documentation

調用$(selector).hover(handlerIn, handlerOut)簡寫爲:

$(selector).mouseenter(handlerIn).mouseleave(handlerOut);

所以你可以解除與

$("#pin_point").off('mouseenter'. hoverhandler).off('mouseleave', hoverhandler); 
+0

我試過了,它不起作用。當第二次點擊#pin_point時。它不會變回到#pin_point img(step1) –

+0

我剛剛在文檔中發現了一些有趣的內容,答案更新了。請現在嘗試。 – bfavaretto

+0

你能告訴我小提琴嗎? –