Change the image source on rollover using jQuery

前端 未结 14 1020
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 10:23

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 t

相关标签:
14条回答
  • 2020-11-22 11:03

    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!

    0 讨论(0)
  • 2020-11-22 11:09
    $('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 :)

    0 讨论(0)
提交回复
热议问题