Change image onmouseover

后端 未结 8 2021
野趣味
野趣味 2021-01-01 21:47

What\'s the correct way to change an image on mouseover and back on mouseout (with/without jQuery)?


    

        
相关标签:
8条回答
  • 2021-01-01 22:32

    You can do that just using CSS.

    You'll need to place another tag inside the <a> and then you can change the CSS background-image attribute on a:hover.

    i.e.

    HTML:

    <a href="#" id="name">
      <span>&nbsp;</span> 
    </a>
    

    CSS:

    a#name span{
      background-image:url(image/path);
    }
    
    a#name:hover span{
      background-image:url(another/image/path);
    }
    
    0 讨论(0)
  • 2021-01-01 22:36

    Try something like this:

    HTML:

    <img src='/folder/image1.jpg' id='imageid'/>
    

    jQuery:

    $('#imageid').hover(function() {
      $(this).attr('src', '/folder/image2.jpg');
    }, function() {
      $(this).attr('src', '/folder/image1.jpg');
    });
    
    • DEMO

    EDIT: (After OP HTML posted)

    HTML:

    <a href="#" id="name">
        <img title="Hello" src="/ico/view.png"/>
    </a>
    

    jQuery:

    $('#name img').hover(function() {
      $(this).attr('src', '/ico/view1.png');
    }, function() {
      $(this).attr('src', '/ico/view.png');
    });
    
    • DEMO
    0 讨论(0)
  • 2021-01-01 22:38

    jQuery has .mouseover() and .html(). You can tie the mouseover event to a function:

    1. Hides the current image.
    2. Replaces the current html image with the one you want to toggle.
    3. Shows the div that you hid.

    The same thing can be done when you get the mouseover event indicating that the cursor is no longer hanging over the div.

    0 讨论(0)
  • 2021-01-01 22:40

    I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img, without "wrapping" it into the a tag (so instead of the document.MyImage, I used this.src)

    <img 
    onMouseOver="this.src='ico/view.hover.png';" 
    onMouseOut="this.src='ico/view.png';" 
    src="ico/view.png" alt="hover effect" />
    

    It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

    0 讨论(0)
  • 2021-01-01 22:42

    Thy to put a dot or two before the /

    ('src','./ico/view.hover.png')"
    
    0 讨论(0)
  • 2021-01-01 22:52

    here's a native javascript inline code to change image onmouseover & onmouseout:

    <a href="#" id="name">
        <img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
    </a>
    
    0 讨论(0)
提交回复
热议问题