Change the image source on rollover using jQuery

前端 未结 14 1003
隐瞒了意图╮
隐瞒了意图╮ 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 10:43

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

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

    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>
    
    0 讨论(0)
  • 2020-11-22 10:46
    <img src="img1.jpg" data-swap="img2.jpg"/>
    
    
    
    img = {
    
     init: function() {
      $('img').on('mouseover', img.swap);
      $('img').on('mouseover', img.swap);
     }, 
    
     swap: function() {
      var tmp = $(this).data('swap');
      $(this).attr('data-swap', $(this).attr('src'));
      $(this).attr('str', tmp);
     }
    }
    
    img.init();
    
    0 讨论(0)
  • 2020-11-22 10:47
        /* Teaser image swap function */
        $('img.swap').hover(function () {
            this.src = '/images/signup_big_hover.png';
        }, function () {
            this.src = '/images/signup_big.png';
        });
    
    0 讨论(0)
  • 2020-11-22 10:48

    I was hoping for an über one liner like:

    $("img.screenshot").attr("src", $(this).replace("foo", "bar"));
    
    0 讨论(0)
提交回复
热议问题