一个更好的实现褪色图像交换与javascript / jQuery

A better implementation of a fading image swap with javascript / jQuery

本文关键字:交换 图像 javascript jQuery 褪色 实现 一个 更好      更新时间:2023-09-26

这不是一个具体的问题或错误,而是一个实现问题。

首先我想说的是,我已经通过了很多褪色的图像教程,我有不同种类的基本了解。我希望这不会和其他数百个关于图像褪色的问题一起被扔出去。

这基本上是我想要的:一个图像褪色到另一个图像在悬停使用javascript,最好是jQuery。我将创建两个图像——一个名为image.jpg,另一个名为image_o.jpg。它们将驻留在同一个文件夹中。

html标记应该是这样的:

<img class="imghover" src="image.jpg" />

javascript将要求我有imghover类上的所有图像,我想悬停。该脚本将检测名为imghover_o.jpg的第二个图像,并将其用于悬停渐变过渡中的第二个图像。

没有必要的CSS或background-image的过渡。

我将有几个这样的图像在一个网格中,他们都需要有渐变过渡。所以,你可以看到,我不想为每个图像创建一个新的CSS类,或者有额外的脚本和html标记,这会变得麻烦。

以上都是通过丹尼尔·诺兰的剧本减去渐变过渡实现的。该脚本只是交换图像,没有褪色,但它是完美的设置与最少的代码。

所以你可以说我只是想给丹尼尔·诺兰的翻页脚本添加一个渐变过渡。是否可以使用jQuery重新制作他的脚本?

这是可能的(与jQuery)?

我将在

您可以获得图像的src属性,并使用.replace()来替换悬停上的url !

工作演示
$('.fadein').each(function() {
    var std = $(this).attr("src");
    var hover = std.replace(".jpg", "_o.jpg"); 
    $(this).clone().insertAfter(this).attr('src', hover).removeClass('fadein').siblings().css({
        position:'absolute'
    });
    $(this).mouseenter(function() {
        $(this).stop().fadeTo(600, 0);
    }).mouseleave(function() {
        $(this).stop().fadeTo(600, 1);
    });
});

或像:

$('.fadein').each(function() {  
    var std = $(this).attr("src");
    var hover = std.replace(".jpg", "_o.jpg");
    $(this).wrap('<div />').clone().insertAfter(this).attr('src', hover).removeClass('fadein').siblings().css({
        position:'absolute'
    });
    $(this).mouseenter(function() {
        $(this).stop().fadeTo(600, 0);
    }).mouseleave(function() {
        $(this).stop().fadeTo(600, 1);
    });
});

脚本的作用:

    var std = $(this).attr("src");抓取SRC属性
  • 将imagered_ .jpg替换为imagered_ .jpg: var hover = std.replace(".jpg", "_o.jpg");
  • 我们必须将第一张图像包装成元素$(this).wrap('<div />')
  • 现在我们可以克隆这个图像并给它一个不同的src并把它放在第一个.clone().insertAfter(this).attr('src', hover)
  • 的下面
  • ,我们必须从第二个图像中删除类'。Fadein '(只有第一张图片会有这个类!).removeClass('fadein')
  • 在我们克隆了这个图像之后,我们通过给它分配一个css绝对位置来设置这个图像:.siblings().css({position:'absolute'});
  • 然后在鼠标进入/离开,我们可以玩第一个图像的可见性。

这里有一个很好的模式:

<img src="http://i.imgur.com/vdDQgb.jpg" hoverImg="http://i.imgur.com/Epl4db.jpg">

JS:

$('body').find('*[hoverImg]').each(function(index){
    $this = $(this)
    $this.wrap('<div>')     
    $this.parent().css('width',$this.width())  
    $this.parent().css('height',$this.width())
    $this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
        $this.hover(function() {
            $(this).stop()
            $(this).fadeTo('',.01)    
        },function() {
            $(this).stop()
            $(this).fadeTo('',1)             
        })                    
});

尽量做到简单一点:

 $('#img').hover(
     function() {
       $(this).stop().fadeIn(...).attr('src', 'image_o').fadeOut(...)
     }, 
     function() {
       $(this).stop().fadeIn(...).attr('src', 'image').fadeOut(...)
 });