使用jQuery更改图片来源

jQuery HTML

JinJin伽罗

2020-03-20

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

原始图片: Image.gif

展期图片: Imageover.gif

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

如何使用jQuery?

第2440篇《使用jQuery更改图片来源》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
JinJin猿 2020.03.20

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.

<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>
达蒙西里村村 2020.03.20

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.

.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 0px coordinates will be the left upper corner from your sprites.

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

Have fun!

StafanDavaidSam 2020.03.20

I was hoping for an über one liner like:

$("img.screenshot").attr("src", $(this).replace("foo", "bar"));
小宇宙神乐Mandy 2020.03.20

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android