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

原始图片:Image.gif 翻转图像:Imageover.gif

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

如何使用jQuery来实现它?


当前回答

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

其他回答

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

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

改编自Richard Ayotte的代码- 要在ul/li列表中定位img(通过包装器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') }
); 

在寻找解决方案的时候,我发现了一个类似于下面的脚本,经过一些调整后,我得到了为我工作。

它处理两个图像,几乎总是默认为“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>
    /* Teaser image swap function */
    $('img.swap').hover(function () {
        this.src = '/images/signup_big_hover.png';
    }, function () {
        this.src = '/images/signup_big.png';
    });