hover on text link to change image

后端 未结 2 1489
半阙折子戏
半阙折子戏 2020-12-22 02:29

I\'m working on a project and need to work out some simple jquery for a text rollover that changes the image in the div behind it.

See the idea here - http://sharif

相关标签:
2条回答
  • 2020-12-22 03:27

    This is just an outline of what you could do. On hover, we create a new img that will hold the necessary image and append it to #slider. The new img needs absolute positioning to appear on top of the previous image (we need this for fading). When mouse leaves the link, we just remove the img.

    Change your HTML like this (add the corresponding image's URL to a data- attribute):

    <a class="hoverlink" data-img="../images/flinders_house.jpg" href="...
    

    And some jQuery:

    var $slider=$('#slider'); //we save the slider
    var $defaultimage=$('img', $slider); //and the default image
    
    //mouseenter for the link
    $('#projects .hoverlink').hover(function () { 
      var filename=$(this).attr('data-img'); //we get the filename from data-img
    
      $('<img id="hoverimage" src="'+filename+'" alt="" />')
        .appendTo($slider).fadeIn(500); //append and fade in new image (#hoverimage)
    
      $defaultimage.fadeOut(500); //fade out default image
    }, 
    //mouseleave for the link
    function () { 
      $('#hoverimage').fadeOut(500, function () { //fade out #hoverimage
        $(this).remove(); //when animation is done, remove it
      });
    
      $defaultimage.fadeIn(500); //meanwhile fade in original image
    });
    

    Also we need some CSS changes:

    /* #hoverimage needs to appear on top of default image */
    #slider { position: relative; }
    #hoverimage { position: absolute; top: 0; left: 0; z-index: 100; }
    

    NOTE: I haven't taken into consideration the loading time for these quite big images, my code assumes they are already cached. You could either do some preloading, or only start the fading effects when the image has loaded (.load()). The latter is not reliable in Opera if I remember well.

    0 讨论(0)
  • 2020-12-22 03:29

    Hmz considering I understood corectly you want this:

    HTML

    <ul id="nav">
        <li><h3><a href="ideas.html">IDEAS</a></h3></li>
        <li><h3><a href="projects.html">PROJECTS</a></h3></li>
        <li><h3><a href="studio.html">STUDIO</a></h3></li>
    </ul>
    

    JS

    $("#nav").hover(function(){$('#slider').hide();}, function(){$('#slider').show()});
    
    0 讨论(0)
提交回复
热议问题