jQuery不和类

时间:2010-05-17 08:30:07

标签: jquery class jquery-plugins fade

我有2个锚链接(a.selector),当点击一个时,它有一个应用于'active-arrow'的类,点击也会从其他锚中删除同名的类以及降低不透明度为0.2。

然后,当用户将鼠标悬停在没有应用“主动箭头”的锚点上时,我想要一个淡入淡出效果,这样当鼠标移动时它会变为完全不透明,当鼠标移动时会变回0.2。

我遇到的问题是,。不:不似乎没有按预期工作,悬停效果有效,但如果我点击锚点虽然应用了悬停'active-arrow'类,但是当鼠标移动时,即使应用了'active-arrow'类,不透明度也会再次降低到0.2。此外,悬停对于另一个已删除“活动箭头”的链接不起作用。

有点难以解释,因此有些代码可能会有所帮助。

*//If a.selector doesn't have the class 'active-arrow' then run the hoverFade function*
$("a.selector").not(".active-arrow").hoverFade();

//Functions for first element
        $('a.selector-1').click(function () {
            $('a.selector-2').removeClass('active-arrow'); //Remove background image from corresponding element
            $('ul#storage-items-2').fadeOut(1200).addClass('hide'); //Fade out then hide corresponding list
            $(this).addClass('active-arrow', 'fast'); //Add background image to current element
            $('ul#storage-items-1').removeClass('hide').fadeIn(1800); //Unhide and fade in the list
            $('a.selector-2').fadeTo(500, 0.2); //Fade corresponding element
            $(this).fadeTo(800, 1);//Fade this element to full opacity
        });

我只包含第一个锚(a.selector-1)的代码,因为第二个锚的代码是相同的,但只是将类名更改为a.selector-2。

hoverFade功能也在一个单独的文件中,因此我们可以重复使用它。

    jQuery.fn.hoverFade = function() {
return this.each(function(){
        $(this).hover(
                function () {
                    $(this).fadeTo(500, 0.8);
            }, 
                function () {
                    $(this).fadeTo(500, 0.2);
        });
  });

}

每个锚链接都淡入并淡出UL。

非常感谢任何帮助

由于

贾尔斯

1 个答案:

答案 0 :(得分:2)

这是您要使用.live().delegate()的情况,如下所示:

$("a.selector:not(.active-arrow)").live('mouseenter', function () {
  $(this).fadeTo(500, 0.8);
}).live('mouseleave', function () {
  $(this).fadeTo(500, 0.2);
});

如果您使用.delegate(),则第一行看起来像这样(ID =所有这些链接的共享父ID的ID):

$("#ID").delegate("a.selector:not(.active-arrow)", 'mouseenter', function () {

你当前拥有的不起作用的原因是它将事件处理程序绑定到元素,当你找到绑定时,元素只需匹配你使用的选择器 ,一旦发生这种情况,.hover() mouseentermouseleave事件处理程序就会绑定在该元素上。课程后来改变的事实并不重要,处理程序可以留下来。

使用上述方法,事件实际上并不直接位于元素上,如果是document,则它们位于父级.live()#ID {1}}。当鼠标事件发生在他们冒泡的元素上,并且父母看到它们时,检查处理程序的选择器是否匹配然后,如果是,则执行。这使得类更改实际上很重要,因为它在事件发生时进行检查,而不是在绑定时进行检查。