2014-03-28 22 views
1

我想知道如果jQuery的'这''可以简化我的代码吗?jQuery使用'this' - 缩略图交换图像,Twitter Bootstrap

这里的完整代码 http://bootsnipp.com/snippets/7ORr

感谢您的帮助,任何建议表示赞赏。

jQuery代码

/* 
Ref: http://api.jquery.com/hover/ 
Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: 
$(selector).mouseenter(handlerIn).mouseleave(handlerOut); 
*/ 

$(document).ready(function() { 

    $('.fd-fade1').hover(function() { 
     // img1 
     $('img.fd-img1').fadeIn('slow'); 
    }, 
    function() { 
     $("img.fd-img1").fadeOut("slow"); 
    }); 

    // img2 
    $('.fd-fade2').hover(function() { 
     $('img.fd-img2').fadeIn('slow'); 
    }, 
    function() { 
     $("img.fd-img2").fadeOut("slow"); 
    }); 

    // img3 
    $('.fd-fade3').hover(function() { 
     $('img.fd-img3').fadeIn('slow'); 
    }, 
    function() { 
     $("img.fd-img3").fadeOut("slow"); 
    }); 

}); // end document.ready function 
+0

jQuery's'this'?你是什​​么意思?每个JS都有一个'this''变量“,它与jQuery无关。最好的改进可能是将相关元素的选择符存储在'data- *'属性中,然后使用'$($(this).data('related'))''来获得对它的引用。 –

+0

是的,它可以......请发布HTML标记,而不是链接到bootsnipp – tymeJV

回答

1

是的,你当然可以使用this凝聚你的代码。例如,如果添加了.fading类所有父母的图像<div>元素,你想淡入/淡出,让你的每一个HTML看起来是这样的:

<div class="fd-fade1 fading"> 
    <img src="http://i.imgur.com/yxAxCaK.jpg" class="fd-img1" alt=""> 
</div> 

那么只需要一组在JavaScript hover()回调做退色效果,通过利用回调语境与this

$(document).ready(function() { 
    $('.fading').hover(function() { 
     $(this).children("img").fadeIn('slow'); 
    }, function() { 
     $(this).children("img").fadeOut("slow"); 
    }); 
}); 

这里有一个JSFiddle展示在行动代码。

哦,对了,如果你想阻止衰落的链接(不知道你注意到没有发生),你可以使用jQuery的stop()时右褪色,像这样前:

$(this).children("img").stop().fadeIn('slow'); 
$(this).children("img").stop().fadeOut("slow"); 

希望这帮助!如果您有任何问题,请告诉我。

+0

我看了[链接](http://api.jquery.com/stop/)并尝试了这两行。但我不明白为什么我会。停止动画,我将“缓慢”改为4000以查看链接效果。但我没有注意到有什么不同,我希望图像淡出,而另一幅图像正在消失。我不了解什么。谢谢。 – mrmccormack

+0

哦,好吧,如果你反复快速地移动你的鼠标移动到图像上,你可能会发现动画在队列中堆积 - 为了阻止这种情况发生,stop()会清除队列,所以停止将图像悬停后,动画将不会继续播放。 – Serlite

+0

下面是在完整代码中使用'stop()'的示例,您可以将它与不带'stop()'的JSFiddle进行比较。 http://jsfiddle.net/jHUV7/1/ – Serlite