javascript - jQuery 使用 'this' - 缩略图交换图像,Twitter Bootstrap

标签 javascript jquery twitter-bootstrap

我想知道 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/

相关文章:

javascript - 在 html 标签中禁用 js

javascript - 如何在窗口调整大小时更新粘性菜单的 CSS 定位

css - 复选框在模式下不起作用

android - CSS 布局是如何变得流畅的?

html - 图像未定位到中心

javascript - 如何使用 eclipse 编辑 Extjs5 响应式应用程序示例项目

javascript - 函数返回数字,但对象被存储

javascript - 模态重叠内容并使内容在 Bootstrap 中不可点击?

javascript - 使用 JQuery 隐藏 div - 不起作用

javascript - 在 chrome 中打印 div,css 不起作用