我想知道 jQuery 的 'this' 是否可以简化我的代码?
完整代码在这里 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
最佳答案
是的,您当然可以使用this
来压缩您的代码。例如,如果您添加了 .fading
给所有家长上课<div>
您想要淡入/淡出的图像元素,因此每个图像的 HTML 如下所示:
<div class="fd-fade1 fading">
<img src="http://i.imgur.com/yxAxCaK.jpg" class="fd-img1" alt="">
</div>
那么您只需要一组 hover()
JavaScript 中的回调通过 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");
希望这有帮助!如果您有任何疑问,请告诉我。
关于javascript - jQuery 使用 'this' - 缩略图交换图像,Twitter Bootstrap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22702324/