使用jQuery更改图片来源

博客讨论了如何使用jQuery在鼠标悬停时实现图片的翻转效果。提供了多种不同的解决方案,包括直接在HTML中添加事件处理,使用CSS类切换,以及通过修改图像源来实现。建议使用CSS精灵或动画按钮以提高性能,特别是在处理多个图像时。
摘要由CSDN通过智能技术生成

我有一些图像及其翻转图像。 我想使用jQuery在onmousemove / onmouseout事件发生时显示/隐藏过渡图像。 我所有的图像名称都遵循相同的模式,如下所示:

原始图片: Image.gif

展期图片: Imageover.gif

我想分别在onmouseover和onmouseout事件中插入和删除图像源的“结束”部分。

我该如何使用jQuery?


#1楼

不将您限制为仅“此图像”和“该图像”的通用解决方案可能是在HTML代码本身中添加“ onmouseover”和“ onmouseout”标签。

的HTML

<img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />

的JavaScript

function swap(newImg){
  this.src = newImg;
}

根据您的设置,也许类似的方法会更好(并且需要更少的HTML修改)。

的HTML

<img src="img1.jpg" id="ref1" />
<img src="img3.jpg" id="ref2" />
<img src="img5.jpg" id="ref3" />

JavaScript / jQuery

// Declare Arrays
  imgList = new Array();
  imgList["ref1"] = new Array();
  imgList["ref2"] = new Array();
  imgList["ref3"] = new Array();

//Set values for each mouse state
  imgList["ref1"]["out"] = "img1.jpg";
  imgList["ref1"]["over"] = "img2.jpg";
  imgList["ref2"]["out"] = "img3.jpg";
  imgList["ref2"]["over"] = "img4.jpg";
  imgList["ref3"]["out"] = "img5.jpg";
  imgList["ref3"]["over"] = "img6.jpg";

//Add the swapping functions
  $("img").mouseover(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
  }

  $("img").mouseout(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
  }

#2楼

<img src="img1.jpg" data-swap="img2.jpg"/>



img = {

 init: function() {
  $('img').on('mouseover', img.swap);
  $('img').on('mouseover', img.swap);
 }, 

 swap: function() {
  var tmp = $(this).data('swap');
  $(this).attr('data-swap', $(this).attr('src'));
  $(this).attr('str', tmp);
 }
}

img.init();

#3楼

    /* Teaser image swap function */
    $('img.swap').hover(function () {
        this.src = '/images/signup_big_hover.png';
    }, function () {
        this.src = '/images/signup_big.png';
    });

#4楼

在寻找解决方案的同时,我发现了与下面类似的脚本,经过一些调整后,我开始为我工作。

它处理两个图像,几乎总是默认为“ off”(鼠标不在图像上)(image-example_off.jpg),以及偶尔的“ on”(在鼠标悬停的时候)所需要的替代图像( image-example_on.jpg)。

<script type="text/javascript">        
    $(document).ready(function() {        
        $("img", this).hover(swapImageIn, swapImageOut);

        function swapImageIn(e) {
            this.src = this.src.replace("_off", "_on");
        }
        function swapImageOut (e) {
            this.src = this.src.replace("_on", "_off");
        }
    });
</script>

#5楼

我做了类似下面的代码:)

仅当您有另一个以_hover命名的文件(例如, facebook.pngfacebook_hover.png

$('#social').find('a').hover(function() {
    var target = $(this).find('img').attr('src');
    //console.log(target);
    var newTarg = target.replace('.png', '_hover.png');
    $(this).find('img').attr("src", newTarg);
}, function() {
    var target = $(this).find('img').attr('src');
    var newTarg = target.replace('_hover.png', '.png');
    $(this).find('img').attr("src", newTarg);
});

#6楼

改编自Richard Ayotte的代码-要针对ul / li列表中的img(在此处通过wrapper div类找到),类似以下内容:

$('div.navlist li').bind('mouseenter mouseleave', function() {    
    $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'), 
    'data-alt-src':$(this).find('img').attr('src') }
); 

#7楼

我希望有一个像这样的über班轮:

$("img.screenshot").attr("src", $(this).replace("foo", "bar"));

#8楼

要准备就绪,请执行以下操作:

$(function() {
    $("img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
            $(this).attr("src", src);
        })
        .mouseout(function() {
            var src = $(this).attr("src").replace("over.gif", ".gif");
            $(this).attr("src", src);
        });
});

对于使用url图片源的用户:

$(function() {
        $("img")
            .mouseover(function() {
               var src = $(this).attr("src");
               var regex = /_normal.svg/gi;
               src = this.src.replace(regex,'_rollover.svg');
               $(this).attr("src", src);

            })
            .mouseout(function() {
               var src = $(this).attr("src");
               var regex = /_rollover.svg/gi;
               src = this.src.replace(regex,'_normal.svg');
               $(this).attr("src", src);

            });
    });

#9楼

$('img.over').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
    var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
    t.hover(function(){
        $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension   
    }, function(){
        $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
});

您可能要从第一行更改图像的类别。 如果您需要更多图像类别(或其他路径),则可以使用

$('img.over, #container img, img.anotherOver').each(function(){

等等。

它应该工作,我没有测试它:)


#10楼

我知道您在问使用jQuery,但是您可以在使用CSS关闭JavaScript的浏览器中实现相同的效果:

#element {
    width: 100px; /* width of image */
    height: 200px; /* height of image */
    background-image: url(/path/to/image.jpg);
}

#element:hover {
    background-image: url(/path/to/other_image.jpg);
}

有一个较长的描述在这里

然而,更好的是使用精灵: simple-css-image-rollover


#11楼

$('img').mouseover(function(){
  var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
  $(this).attr("src", newSrc); 
});
$('img').mouseout(function(){
  var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
  $(this).attr("src", newSrc); 
});

#12楼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JQuery</title>
<script src="jquery.js" type="text/javascript"> </script>
<style type="text/css">
    #box{
        width: 68px;
        height: 27px;
        background: url(images/home1.gif);
        cursor: pointer;
    }
</style>

<script type="text/javascript">

$(function(){

    $('#box').hover( function(){
        $('#box').css('background', 'url(images/home2.gif)');

    });
    $('#box').mouseout( function(){
        $('#box').css('background', 'url(images/home1.gif)');

    });

});
</script>
</head>

<body>
<div id="box" onclick="location.href='index.php';"></div>
</body>
</html>

#13楼

如果您正在寻找的解决方案是使用动画按钮,那么提高性能的最佳方法就是将Sprite和CSS结合使用。 子画面是一个巨大的图像,其中包含您网站上的所有图像(标题,徽标,按钮以及您拥有的所有装饰)。 您拥有的每个图像都使用一个HTTP请求,并且HTTP请求越多,加载所需的时间就越多。

.buttonClass {
    width: 25px;
    height: 25px;
    background: url(Sprite.gif) -40px -500px;
}
.buttonClass:hover {
    width: 25px;
    height: 25px;
    background: url(Sprite.gif) -40px -525px;
}

0px 0px坐标将位于子0px 0px左上角。

但是,如果您正在使用Ajax或类似的东西来开发相册,那么JavaScript(或任何框架)是最好的。

玩得开心!


#14楼

如果您有多个图像,并且需要某种不依赖命名约定的通用图像。

的HTML

<img data-other-src="big-zebra.jpg" src="small-cat.jpg">
<img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
<img data-other-src="friendly-bear.jpg" src="penguin.jpg">

的JavaScript

$('img').bind('mouseenter mouseleave', function() {
    $(this).attr({
        src: $(this).attr('data-other-src') 
        , 'data-other-src': $(this).attr('src') 
    })
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值