2013-10-16 108 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

你能告诉我小提琴吗? –