开发者

How do I display an image when a user hovers over a link using JQuery

I've got a list of products.

<ul>
<li><a href="chair.php">CHAIR</a></li>
<li><a href="table.php">TABLE</a></li>
<li><a href="sofa.php">SOFA</a></li>
<li><a href="bookshelf.php">BOOKSHELF</a></li>
<ul>

On mouseover I want to display a thumbnail image of the product in a div #preview.

I don't want to hardcode the jquery for each image. Rather I'd like to write JQuer开发者_运维问答y that would grab the image location and insert into the DOM. I have no idea how I would mark up the HTML to include the image location. Any ideas?


I'd suggest using the new HTML5 data attributes, like so:

<a href="chair.php" data-thumbnail-src="chair.jpg">CHAIR</a>

Then you could set up the jQuery code as follows:

$(function () {
    var $preview = $("#preview");

    $("ul#products a").hover(function () {
        $preview.attr("src", $(this).attr("data-thumbnail-src"));
    }, function () {
        $preview.attr("src", "");
    });
});

In jQuery 1.4.3 and higher, I believe $(this).data("thumbnail-src") will also work.


its is old , but i got here with google search . i believe the best solution would be this : http://james.padolsey.com/demos/imgPreview/full/


Hopefully this is a decent solution. Im using the JQuery Metadata plugin

Here is the stuff live : http://jsfiddle.net/giddygeek/VqL65/14/

Html:

<script type="text/javascript" src="https://github.com/jquery/jquery-metadata/raw/master/jquery.metadata.js"></script>
<ul class="pics">
<li class="pic {url:'chair.jpg'}">
    <a href="chair.php">CHAIR</a></li>
<li class="pic {url:'table.jpg'}">
    <a href="table.php">TABLE</a></li>
<li>
    <a href="sofa.php">SOFA</a></li>
<li>
    <a href="bookshelf.php">BOOKSHELF</a></li>
<ul>
<div id="preview">
<img src="" />
<div/>

JQuery

$(document).ready(function()
    {
       $("ul.pics li").hover(
           function()
           {//on hover over
              var data = $(this).metadata();//get the metadata 
               if(data.url) {//check if it exists
                   $("#preview img").attr("src",data.url)//set the url to it
               }

           },
           function()
           {//on hover OUT
               $("#preview img").attr("src","");//set the img src to nothing
           }
           );
    }
);

Notes:

  • Ive heard this is W3C compliant and might be compatible with Html5
  • Do add a class for each <li> named pic {url:'something'}.
  • Set the url to your favorite picture.
  • In the JQuery, the hover out sets the img src to nothing-> "". Here you should set it to a NONE pic or do something else.
  • Oh and download the metadata plugin (I used a raw link from github)

Hope this helped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜