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
被点击时,我也取消绑定(bind)了 #1(上面)中的悬停功能。
问题:如果我想在再次点击#pin_point 时绑定(bind)函数, 我应该怎么办?下面是我的代码,我很难搞清楚。 谁能帮忙?
$("#pin_point").click(function() {
$('#pin_point').unbind('hover', hoverhandler);
$("#pin_point img").attr('src','images/ex.png');
$('#pin_point').bind('hover', hoverhandler);
});
最佳答案
hover
是一个速记事件。而是取消绑定(bind) mousenter
和 mouseleave
。还将状态信息附加到元素以获得每次点击的替代效果。
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,您可以使用 on
和 off
。
关于javascript - 绑定(bind)和解绑函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414330/