JQuery的悬停和点击事件
问题描述:
我有很多的人在页面上的照片,我想通过显示一个人的鼠标替代的照片,并有照片还原到默认的鼠标了。我还希望当有人点击照片以查看他们的个人资料(显示在侧栏上)时显示替代照片。当有人点击不同的人时,默认的照片将出现给该人。我无法将点击和悬停事件相结合来实现此目的。JQuery的悬停和点击事件
这是我到目前为止所。我在那里参加派对,但是这不会将先前查看的个人资料图片恢复为默认照片。点击不同的个人资料照片时,如何从先前查看的个人资料中删除点击事件?
$('.rollover').click(function() {
$(this).unbind('mouseout');
}).mouseover(function() {
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
}).mouseout(function() {
$(this).attr('src', img_src); //swap images
$(this).attr('rel', new_src); //swap images
});
在此先感谢。
答
这就是我最终做的工作,正如我想要的那样工作。可能有一种方法来简化这一点,我会接受建议。感谢那些回复。
jQuery(document).ready(function($) {
//rollover swap images with rel
var img_src = "";
var new_src = "";
$('.rollover').click(function() {
if($(this).hasClass("clicked"))
{
//do nothing if this element has already been clicked
}
else
{
//Unbind the hover effect from this element
$(this).removeClass("rollover");
$(this).unbind('mouseenter').unbind('mouseleave')
//Go through and find anything having 'clicked' class -
//in theory, there should only be one element that has the 'clicked' class at any given time.
$('.clicked').each(function(){
$(this).removeClass("clicked");
$(this).addClass("rollover");
//Swap the images
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
//Rebind hover (since we unbound it back up there ^^) to this *specific* element.
//If you do $(".rollover") to rebind, it kills all the other existing binds and binds ONLY this element.
$(this).hover(function(){
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
});
});
$(this).addClass("clicked");
}
});
$(".rollover").hover(function(){
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
});
});
答
您可以通过使用on
方法绑定一个单击处理。
$(document).on({
mouseenter: function() {
img_src = $(this).attr('src');
new_src = $(this).attr('rel');
$(this).attr('src', new_src);
$(this).attr('rel', img_src);
},
mouseleave: function() {
$(this).attr('src', img_src);
$(this).attr('rel', new_src);
},
click: function() {
// ...
},
}, ".rollover");
感谢您的答复,但这种缺少解除绑定事件。我用我的进步更新了我的问题。 – brett