使用 jQuery 更改翻转时的图像源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/540349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:18:16  来源:igfitidea点击:

Change the image source on rollover using jQuery

jqueryhtml

提问by Sachin Gaur

I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:

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

Original Image: Image.gif

Rollover Image: Imageover.gif

原图: Image.gif

翻转图像: Imageover.gif

I want to insert and remove the "over"portion of image source in the onmouseover and onmouseout event, respectively.

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

How can I do it using jQuery?

我如何使用 jQuery 做到这一点?

回答by Jarrod Dixon

To set up on ready:

要设置就绪:

$(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);
        });
});

For those that use url image sources:

对于那些使用 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);

            });
    });

回答by Tyson

I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:

我知道您在询问使用 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);
}

There's a longer description here

有一个较长的描述在这里

Even better, however, is to use sprites: simple-css-image-rollover

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

回答by Richard Ayotte

If you have more than one image and you need something generic that doesn't depend on a naming convention.

如果您有多个图像并且您需要一些不依赖于命名约定的通用图像。

HTML

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

JavaScript

$('img').bind('mouseenter mouseleave', function() {
    $(this).attr({
        src: $(this).attr('data-other-src') 
        , 'data-other-src': $(this).attr('src') 
    })
});

回答by jonasl

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

回答by DACrosby

A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.

一个不限制您只使用“这个图像”和“那个图像”的通用解决方案可能是将“onmouseover”和“onmouseout”标签添加到 HTML 代码本身。

HTML

HTML

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

JavaScript

JavaScript

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


Depending on your setup, maybe something like this would work better (and requires less HTML modification).

根据您的设置,也许这​​样的事情会更好(并且需要更少的 HTML 修改)。

HTML

HTML

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

JavaScript / jQuery

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"]);
  }

回答by Ionu? Staicu

$('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
    });
});

You may want to change the class of images from first line. If you need more image classes (or different path) you may use

您可能希望从第一行更改图像类别。如果您需要更多图像类(或不同路径),您可以使用

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

and so on.

等等。

It should work, I didn't test it :)

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

回答by chovy

I was hoping for an über one liner like:

我希望有一个像这样的超级单班轮:

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

回答by matt

If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.

如果您正在寻找的解决方案是动画按钮,那么您可以做的最好的改进性能是 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;
}

The 0px 0pxcoordinates will be the left upper corner from your sprites.

0px 0px坐标将是你的精灵左上角。

But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.

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

Have fun!

玩得开心!

回答by iamrasec

$('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); 
});

回答by Kristopher Rout

Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.

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

It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.

它处理两个图像,几乎总是默认为“关闭”,鼠标离开图像(image-example_off.jpg),偶尔“打开”,鼠标悬停时,所需的替代图像( 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>