Change the image source on rollover using jQuery

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

    A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.

    HTML

    
    

    JavaScript

    function swap(newImg){
      this.src = newImg;
    }
    

    Depending on your setup, maybe something like this would work better (and requires less HTML modification).

    HTML

    
    
    
    

    JavaScript / jQuery

    // Declare Arrays
      imgList = new Array();
      imgList["ref1"] = new Array();
      imgList["ref2"] = new Array();
      imgList["ref3"] = new Array();
    
    //Set values for each mouse state
      imgList["ref1"]["out"] = "img1.jpg";
      imgList["ref1"]["over"] = "img2.jpg";
      imgList["ref2"]["out"] = "img3.jpg";
      imgList["ref2"]["over"] = "img4.jpg";
      imgList["ref3"]["out"] = "img5.jpg";
      imgList["ref3"]["over"] = "img6.jpg";
    
    //Add the swapping functions
      $("img").mouseover(function(){
        $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
      }
    
      $("img").mouseout(function(){
        $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
      }
    

提交回复
热议问题