1

我有一个带有 PNG 图标的菜单。我希望当用户悬停菜单项时,PNG 图标更改为 GIF 图标。我试过这个: jsFiddle

$("#image").mouseenter(function(){
    // I can set GIF url here
    $(this).attr("src","http://jsfiddle.net/img/logo.png");
});

$("#image").mouseleave(function(){
    $(this).attr("src","http://jsfiddle.net/img/logo-white.png");
});

但我知道这不是正确的方法。我不能对每个菜单项都这样做。这是我的 HTML:

<ul>
    <li>
        <a> item 1
        <img src="image-path" />
        </a>
    </li>
    <li>
        <a> item 2
        <img src="image-path" />
        </a>
    </li>
</ul>

我关注了这个问题,但这不是我想要的。我想在路径的最后一个.或最后一个拆分。/

此代码在每个字符上拆分字符串/

var data =$("#image").attr("src");
var array = data.split('/');

问题:

我有这个图像路径:../images/icon1.png我想将其更改为这些路径:

../images/icon1.gif或者../images/hover/icon1.gif

4

6 回答 6

3

这不需要js。

它可以简单地使用 css 来完成。

image{background-image:url(../images/icon.png);}
image:hover{background-image:url(../images/icon1.png);}
于 2013-10-22T07:06:15.280 回答
3

尝试

$('ul img').hover(function (e) {
    $(this).attr('src', function (idx, src) {
        return src.replace(/(.)(png|gif)$/i, '.' + (e.type == 'mouseenter' ? 'gif': 'png'))
    })
})

演示:小提琴

于 2013-10-22T07:09:47.847 回答
1

只需剪掉最后三个字符:

var oldSrc = this.src;
this.src = oldSrc.substr(0,oldSrc.length-3)+"png";
// or +"gif" to change to the GIF image.
于 2013-10-22T07:05:59.630 回答
1

这成功了吗?

$(this).attr('src', 'http://jsfiddle.net/img/logo-white.png'); 
于 2013-10-22T07:07:29.677 回答
1

Hiral 是正确的,你不需要 JS。

尝试以下操作:

.icon {
    width: 32px; /* Replace with your own */
    height: 32px; /* Replace with your own */
}
.icon-house {
    background-image:url(../images/icon-house.png);
}
.icon-house:hover {
    background-image:url(../images/icon-house-hover.png);
}
.icon-car {
    background-image:url(../images/icon-car.png);
}
.icon-car:hover {
    background-image:url(../images/icon-car-hover.png);
}
/* etc... */

并将您的 HTML 更改为如下内容:

<ul>
    <li>
        <a href="index.html">Home
        <span class="icon icon-house"></span>
        </a>
    </li>
    <li>
        <a href="carsrock.html">Cars are awesome!
        <span class="icon icon-car"></span>
        </a>
    </li>
</ul>

或者,您可以使用 spritesheet,这也可以为您的用户节省时间,因为他们不需要下载许多单独的小图像。

这篇文章是相关的:http ://css-tricks.com/css-sprites/

于 2013-10-22T07:15:46.610 回答
0

您可以使用正则表达式来替换路径:

var newSrc = $(this).attr("src").replace(/\.png$/, ".gif");
$(this).attr("src", newSrc);
于 2013-10-22T07:17:53.033 回答