ibcadmin 发表于 2013-1-7 17:19:51

jQuery实现图片预览鼠标放上去以后预览

效果大家以前可能已经见过了,现在主要结合jQuery说明一下实现原理。

html显示原始图片

<a href="../images/4.jpg" class="preview" title="疯狂滑雪">
<img src="../images/4s.jpg" /></a>
<a href="../images/photo_1.jpg" class="preview" title="奥运吉祥物">
<img width="100" height="75" src="../images/photo_1_small.gif"/></a>


以下是jQuery实现图片预览的主要过程。
hover()事件


xOffset = 10;
yOffset = 30;
$("a.preview").hover(function(e){
    this.t = this.title;
    this.title = "";       
    var c = (this.t != "") ? "<br/>" + this.t : "";
    $("body").append("<p id='preview'><img src='"
      + this.href +"' alt='Image preview' />"+ c +"</p>");
    $("#preview")
       .css("top",(e.pageY - xOffset) + "px")
       .css("left",(e.pageX + yOffset) + "px")
       .fadeIn("fast");

    },function(){
      this.title = this.t;
      $("#preview").remove();
    });       


程序中首先找到预览图片,光标移动到某个图片上时,将此图片的预览图片添加到body中,将id命名为preview。preview开始是不可见的,.css()为图片指定了位置,.fadeIn()最终显示预览图片。当光标离开图片时,将添加的预览图片使用remove()方法移除。


使用mousemove()方法移动鼠标时移动预览最后,当鼠标在图片上移动时,应该使用mousemove()方法将图片预览也进行移动。

$("a.preview").mousemove(function(e){
    $("#preview")
      .css("top",(e.pageY - xOffset) + "px")
      .css("left",(e.pageX + yOffset) + "px");
});       

jQuery实现图片预览的完整代码

this.imagePreview = function(){
    xOffset = 10;
    yOffset = 30;
    $("a.preview").hover(function(e){
      this.t = this.title;
      this.title = "";
      var c = (this.t != "") ? "<br/>" + this.t : "";
      $("body").append("<p id='preview'><img src='"
                + this.href +"' alt='Image preview' />"+ c +"</p>");
      $("#preview")
            .css("top",(e.pageY - xOffset) + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
    },function(){
      this.title = this.t;
      $("#preview").remove();
    });   
    $("a.preview").mousemove(function(e){
      $("#preview")
            .css("top",(e.pageY - xOffset) + "px")
            .css("left",(e.pageX + yOffset) + "px");
    });       
};

页: [1]
查看完整版本: jQuery实现图片预览鼠标放上去以后预览