通过编写适当的 JavaScript 函数来简化我的代码

Simplify my code by coding a proper javascript function

本文关键字:函数 代码 我的 JavaScript      更新时间:2023-09-26

我有以下关于将参数传递给函数波纹管的问题。

目前完成的方式:

当鼠标悬停时,我在两个图像之间获得了过渡效果。我需要每个图像 1 个函数,因为每个图像的路径不同,我使用不同的类来区分所有图像。

Javascript:

</script>    
    $(function() {
    $(".fade_image1")
    .find("span")
        .hide()
        .end()
        .hover(function() {
            $(this).find("span").stop(true, true).fadeIn();
        }, function() {
            $(this).find("span").stop(true, true).fadeOut();
         });
    });
    $(function() {
    $(".fade_image2")
        .find("span")
        .hide()
        .end()
        .hover(function() {
            $(this).find("span").stop(true, true).fadeIn();
                     }, function() {
            $(this).find("span").stop(true, true).fadeOut();
        });
    });
</script>

.HTML:

<div>
  <a href="#" class="fade_image1">Image<span></span></a>
</div>
<div>
  <a href="#" class="fade_image2">Image<span></span></a>
</div>

.CSS:

.fade_image1{
display: inline-block;
position: relative;
text-indent: -9999px;
width: 303px;
height: 605px;
background: url(images/20130128_UK_Colour-Campaign_cropped_02.jpg) no-repeat;
}
.fade_image1 span {
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background: url(images/images-rollover/20130128_UK_Colour-Campaign_cropped-rollover_02.jpg) no-repeat;
/*background-position: -50px 0;*/
}
.fade_image2{
display: inline-block;
position: relative;
text-indent: -9999px;
width: 608px;
height: 302px;
background: url(images/20130128_UK_Colour-Campaign_cropped_03.jpg) no-repeat;
}
.fade_image2 span {
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background: url(images/images-rollover/20130128_UK_Colour-Campaign_cropped-rollover_03.jpg) no-repeat;
/*background-position: -50px 0;*/
}

所以这是我的问题,如何通过只有 1 个 javascript 函数适用于所有图像来简化它?我知道我需要将图像的路径传递到函数中,然后我可以使用 JQuery 的 css 内容,但我不知道更多:)

所以请帮我:)

这应该适合您的需求:

$(function() {
    function setupFade(selector) {
        $(selector)
        .find("span")
        .hide()
        .end()
        .hover(function() {
            $(this).find("span").stop(true, true).fadeIn();
        }, function() {
            $(this).find("span").stop(true, true).fadeOut();
        });
    }
    setupFade(".fade_image1");
    setupFade(".fade_image2");
});

一个setupFade函数,但两个调用。

这里有两个选项:

只需向图像添加一个类,然后使用此函数:

$(function() {
$(".fade_images")
    .find("span")
    .hide()
    .end()
    .hover(
        function() {
            $(this).find("span").stop(true, true).fadeIn();
        }, function() {
            $(this).find("span").stop(true, true).fadeOut();
        }
    );
});

添加的类:

<a href="#" class="fade_image1 fade_images">Image<span></span></a>

或者,检查类以 "fade_image" 开头的 <a> 标记,而不是向所有图像添加类:

$(function() {
$('a[class^=fade_image]') //<-- for all <a> tags whom class starts with `fade_img`. use *= instead of ^= if you need to filter for "Contains" instead of "Starts with".
    .find("span")
    // Etc...