基于jQuery实现放大镜效果

 更新时间:2015年12月21日 10:01  点击:1282

相信大家都见过或使用过放大镜效果,甚至实现过该效果,它一般应用于放大查看商品图片,一些电商网站(例如:凡客,京东商城,阿里巴巴等)都有类似的图片查看效果。

在接下来的文章中,我们将向大家介绍通过jQuery实现放大镜效果。

1、实现原理
首先,我们讲解一下放大镜效果的实现方式:

方法一:准备一张高像素的大图,当鼠标放到原图上,加载显示大图的对应位置。

方法二:对原图片进行放大,也就是调整原图的长和宽。

上面我们介绍了通过两种方式实现放大镜效果,接下来,我们将以上的两种方式应用到我们的jQuery插件中。

首先,我们需要一个img元素显示原图对象,还需要一个容器作为显示框;显示框里面存放大图对象。当鼠标移动到原图上时,通过对大图进行绝对定位来显示对应的部位,实现类似放大镜的效果。

接下来,让我们定义Index.html页面,具体实现如下:

<!doctype html>
<html lang="en-US">
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 <title>jQuery Image Zoom Demo</title>
 <meta name="author" content="Jackson Huang">
</head>
<body>
<div class="magnify">
<div class="large"></div>
<img class="small" src="./img/1.jpg" width="700" />
</div>
</body>
</html>

上面,我们定义了small对象用于显示原图,而large对象作为一个显示框用来显示大图的对应位置。

2、mousemove事件
接下来,我们通过jQuery插件形式来实现放大镜效果,当鼠标移动到small对象上方时,就会在large对象中显示大图的对应位置,这就涉及到mousemove事件了,所以,我们需要实现mousemove事件的监听方法(如何定义jQuery插件可以参考《自定义jQuery插件Step by Step》)。

现在,让我们实现jquery.imagezoom.js插件吧!

;
(function ($) {

 $.fn.imageZoom = function (options) {

 // The native width and height of the image.
 var native_width = 0,
  native_height = 0,
  current_width = 0,
  current_height = 0,
  $small = $(".small"),
  $large = $(".large");

 $(".magnify").mousemove(function (e) {
  /* Act on the event */
  if (!native_width && !native_height) {
   var image_object = new Image();
   image_object.src = $small.attr('src');

   // Gets the image native height and width.
   native_height = image_object.height;
   native_width = image_object.width;

   // Gets the image current height and width.
   current_height = $small.height();
   current_width = $small.width();

  } else {

   // Gets .maginfy offset coordinates.
   var magnify_offset = $(this).offset(),

    // Gets coordinates within .maginfy.
    mx = e.pageX - magnify_offset.left,
    my = e.pageY - magnify_offset.top;

   // Checks the mouse within .maginfy or not.
   if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
    $large.fadeIn(100);
   } else {
    $large.fadeOut(100);
   } if ($large.is(":visible")) {
    /* Gets the large image coordinate by ratio 
     small.x / small.width = large.x / large.width
     small.y / small.height = large.y / large.height
     then we need to keep pointer in the centre, 
     so deduct the half of .large width and height.
    */
    var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
     ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
     bgp = rx + "px " + ry + "px",
     px = mx - $large.width() / 2,
     py = my - $large.height() / 2;
    $large.css({
     left: px,
     top: py,
     backgroundPosition: bgp
    });
   }

  }
 });
});

上面,我实现了mousemove事件的监听方法,当鼠标移动到magnify对象中,我们需要获取当前鼠标的相对坐标位置,下面我们通过图片讲解如何获取鼠标的相对坐标位置。

3、相对坐标

图1鼠标相对坐标位置

当鼠标移动到magnify对象中,我们需要获取鼠标在magnify中的相对坐标位置,这里我们把相对坐标定义为(mx,my),通过上图我们知道相对坐标等于(pageX - offsetLeft, pageY - offsetTop)。

现在,我们已经获取鼠标在magnify对象中的坐标值,接下来,需要获取对应大图的相应坐标,这里我们把大图的对应坐标定义为(rx,ry),我们可以通过比例关系获取(rx,ry)的值。

mx / small.width (原图的宽)= rx / native_width(大图的宽)

my / small.height (原图的长)= ry / native_height(大图的长)

通过上面的比例关系,我们知道大图的坐标(rx,ry)等于(mx/small.width*native_width, my/small.height*native_height)。

通过上述的公式,我们可以获取大图对应坐标位置,当鼠标移动到magnify对象中就显示对应位置的大图部位,接下来我们需要实现大图的加载实现了。

4、background-position属性
在实现大图加载显示之前,首先介绍CSS中背景定位background-position的知识。

图2 CSS background-position

上面,有一个100x100像素的图片它由四种颜色组成,而且每种颜色占50 x50像素,接下来,我们将通过修改该图片CSS的background-position属性值来显示该图片的不同位置。

我们看到在大正方形下有两行小正方形,它们显示的颜色位置都不相同,这里我们通过修改每个div元素CSS的background-position属性值实现的。

例如:第一行的蓝色方形,我们设置CSS的background-position属性为:0px -50px;这相当于原图往上移动50px,第一行的其他方形也通过左右和上下移动实现的。

但第二行的方形就显得更加奇怪了,因为它们都由四种颜色组成,而且颜色的位置都不一样,这究竟是怎样实现的呢?

例如:第二行的第一个方形,我们设置CSS的background-position属性为:25px 25px;这相当于原图向下和向右移动了25px,由于image wrap的作用它会填充剩余位置的颜色。

现在,我们已经了解到了CSS的background-position属性的作用,所以我们通过修改large对象的background-position属性来显示对应的图像部分,具体实现如下:

$large.css({
 left: px,
 top: py,
 backgroundPosition: bgp
});

上面,我们通过加载大图的方式来实现放大镜效果,接下来,我们将介绍通过调整原图的长和宽来实现放大镜效果。

5、mousewheel事件
前面,我们通过mousemove事件来放大图片,这里我们将通过鼠标的滚轮事件实现图片放大效果。

由于,不同的浏览器有不同的滚轮事件。主要是有三种:onmousewheel(IE 6/7/8)、mousewheel(IE9,Chrome,Safari和Opera)和DOMMouseScroll(只有Firefox支持),关于这三个事件这里不做详细的介绍了。

由于不同浏览器之间存在着差异,为了实现浏览器之间的兼容,所以,我们需要监听以上三种滚轮事件(onmousewheel,mousewheel和DOMMouseScroll),具体实现如下:

$(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {
});

上面,我们实现了兼容不同浏览器的滚轮事件监听方法,接下来,判断滚轮向上或向下也要考虑不同浏览器的兼容性,主流的览器(IE、Opera、Safari、Firefox、Chrome)中Firefox 使用detail,其余四类使用wheelDelta;两者只在取值上不一致,代表含义一致,detail与wheelDelta只各取两个值,detail只取±3,wheelDelta只取±120,其中正数表示为向上,负数表示向下。

由于detail和wheelDelta都有两个值表示向上或向下滚动,所以不同浏览器间可以通过以下方式实现兼容,具体实现如下:

$(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {

 // cross-browser wheel delta
 var e = window.event || e; // old IE support.
 var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
});

上面,我们已经处理了不同浏览器滚轮监听方法,当用户滚动滚轮时需要动态地修改原图的尺寸,这里我们定义缩放比scaling为0.3,也就是说每当用户滚动一下滚轮原图就按0.3的比例进行缩放,具体实现如下:

// Gets the image scaling height and width.
native_height += (native_height * scaling * delta);
native_width += (native_width * scaling * delta);

// Update backgroud image size.
$large.css('background-size', native_width + "px " + native_height + "px");

现在,我们已经实现了通过滚轮对图片进行缩放查看的效果,完整的实现如下:

(function($) {

 $.fn.imageZoom = function(options) {


  // The native width and height of the image.
  var defaults = {
   scaling: 0.3
  };

  // Combines object defaults and options.
  options = $.extend(defaults, options),
   native_width = 0,
   native_height = 0,
   current_width = 0,
   current_height = 0,
   $small = $(".small"),
   $large = $(".large");

  $(".magnify").mousemove(function(e) {
   /* Act on the event */
   if (!native_width && !native_height) {
    var image_object = new Image();
    image_object.src = $small.attr('src');

    // Gets the image native height and width.
    native_height = image_object.height;
    native_width = image_object.width;

    // Gets the image current height and width.
    current_height = $small.height();
    current_width = $small.width();

   } else {

    // Gets .maginfy offset coordinates.
    var magnify_offset = $(this).offset(),

    // Gets coordinates within .maginfy.
     mx = e.pageX - magnify_offset.left,
     my = e.pageY - magnify_offset.top;

    // Checks the mouse within .maginfy or not.
    if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
     $large.fadeIn(100);
    } else {
     $large.fadeOut(100);
    }
    if ($large.is(":visible")) {
     /* Gets the large image coordinate by ratio 
     small.x / small.width = large.x / large.width
     small.y / small.height = large.y / large.height
     then we need to keep pointer in the centre, 
     so deduct the half of .large width and height.
     */
     var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
      ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
      bgp = rx + "px " + ry + "px",
      px = mx - $large.width() / 2,
      py = my - $large.height() / 2;
     $large.css({
      left: px,
      top: py,
      backgroundPosition: bgp
     });
    }

   }
  });

  $(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {
   var image_object = new Image();
   image_object.src = $large.attr('src');


   // cross-browser wheel delta
   e = window.event || e; // old IE support.
   var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

   // Gets the image scaling height and width.
   native_height += (native_height * defaults.scaling * delta);
   native_width += (native_width * defaults.scaling * delta);

   // The image can't smaller than the original.
   if (native_height < current_height) {
    native_height = current_height;
   }

   if (native_width < current_width) {
    native_width = current_width;
   }

   // console.log("native_height: " + native_height + " native_width: " + native_width);

   // Gets .maginfy offset coordinates.
   var magnify_offset = $(this).offset(),
    mx = e.pageX - magnify_offset.left,
    my = e.pageY - magnify_offset.top;

   // Update backgroud image size.
   $large.css('background-size', native_width + "px " + native_height + "px");

   /* Gets the large image coordinate by ratio 
   small.x / small.width = large.x / large.width
   small.y / small.height = large.y / large.height
   then we need to keep pointer in the centre, 
   so deduct the half of .large width and height.
   */
   var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
    ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
    bgp = rx + "px " + ry + "px",
    px = mx - $large.width() / 2,
    py = my - $large.height() / 2;

   $large.css({
    left: px,
    top: py,
    backgroundPosition: bgp
   });
  });
 };
})(jQuery);
 

上面,我们实现了放大镜效果,当我们鼠标停留在图片上方会自动放大图片的相应部位,当然我们可以通过滚轮调整放大的比例。

在本文中,我们介绍了如何实现放大镜效果,总的来说,我们可以通过两种方式实现放大镜效果,而且在文中都给出了详细的介绍,通过mousemove事件实现加载大图的效果,mousewheel事件实现动态修改原图的尺寸。

这只是一个简单的程序,我们还有很大的改善空间,提供一个内容丰富和功能强大的程序是我们的目标。

以上就是本文的详细内容,希望对大家的学习有所帮助。

[!--infotagslink--]

相关文章

  • jquery实现加载更多"转圈圈"效果(示例代码)

    这篇文章主要介绍了jquery实现加载更多"转圈圈"效果,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-10
  • 自己动手写的jquery分页控件(非常简单实用)

    最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
  • jQuery+jRange实现滑动选取数值范围特效

    有时我们在页面上需要选择数值范围,如购物时选取价格区间,购买主机时自主选取CPU,内存大小配置等,使用直观的滑块条直接选取想要的数值大小即可,无需手动输入数值,操作简单又方便。HTML首先载入jQuery库文件以及jRange相关...2015-03-15
  • jQuery实现非常实用漂亮的select下拉菜单选择效果

    本文实例讲述了jQuery实现非常实用漂亮的select下拉菜单选择效果。分享给大家供大家参考,具体如下:先来看如下运行效果截图:在线演示地址如下:http://demo.jb51.net/js/2015/js-select-chose-style-menu-codes/具体代码如...2015-11-08
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • Jquery Ajax Error 调试错误的技巧

    JQuery使我们在开发Ajax应用程序的时候提高了效率,减少了许多兼容性问题,我们在Ajax项目中,遇到ajax异步获取数据出错怎么办,我们可以通过捕捉error事件来获取出错的信息。在没给大家介绍正文之前先给分享Jquery中AJAX参...2015-11-24
  • jQuery 2.0.3 源码分析之core(一)整体架构

    拜读一个开源框架,最想学到的就是设计的思想和实现的技巧。废话不多说,jquery这么多年了分析都写烂了,老早以前就拜读过,不过这几年都是做移动端,一直御用zepto, 最近抽出点时间把jquery又给扫一遍我也不会照本宣科的翻译...2014-05-31
  • jQuery页面加载初始化常用的三种方法

    当页面打开时我们需要执行一些操作,这个时候如果我们选择使用jquery的话,需要重写他的3中方法,自我感觉没什么区 别,看个人喜好了,第二种感觉比较简单明了: 第一种: 复制代码 代码如下: <script type="text/javas...2014-06-07
  • jquery中常用的SET和GET$(”#msg”).html循环介绍

    复制代码 代码如下: $(”#msg”).html(); //返回id为msg的元素节点的html内容。 $(”#msg”).html(”new content“); //将“new content” 作为html串写入id为msg的元素节点内容中,页面显示粗体的new content $(”...2013-10-13
  • jquery获取div距离窗口和父级dv的距离示例

    jquery中jquery.offset().top / left用于获取div距离窗口的距离,jquery.position().top / left 用于获取距离父级div的距离(必须是绝对定位的div)。 (1)先介绍jquery.offset().top / left css: 复制代码 代码如下: *{ mar...2013-10-13
  • jQuery Mobile开发中日期插件Mobiscroll使用说明

    这篇文章主要介绍了jQuery Mobile开发中日期插件Mobiscroll使用说明,需要的朋友可以参考下...2016-03-03
  • jQuery实现切换页面过渡动画效果

    直接为大家介绍制作过程,希望大家可以喜欢。HTML结构该页面切换特效的HTML结构使用一个<main>元素来作为页面的包裹元素,div.cd-cover-layer用于制作页面切换时的遮罩层,div.cd-loading-bar是进行ajax加载时的loading进...2015-10-30
  • jQuery实现鼠标滑过链接控制图片的滑动展开与隐藏效果

    本文实例讲述了jQuery实现鼠标滑过链接控制图片的滑动展开与隐藏效果。分享给大家供大家参考,具体如下:这里演示jQuery实现鼠标移动到链接上,滑动展开/隐藏图片效果,鼠标放在“上一页”“下一页”上,立即浮现出所对应的图...2015-10-30
  • jQuery+PHP发布的内容进行无刷新分页(Fckeditor)

    这篇文章将使用jQuery,并结合PHP,将Fckeditor发布的内容进行分页,并且实现无刷新切换页面。 本文假设你是WEB开发人员,掌握了jQuery和PHP相关知识,并且熟知Fckeditor的配置和使用。...2015-10-23
  • jQuery实现带玻璃流光质感的手风琴特效

    jQuery实现带玻璃流光质感的手风琴特效是一款基于jQuery+CSS3实现的带玻璃流光质感的手风琴特效,分享给大家,具体如下效果图:具体代码如下:html代码: <section class="strips"> <article class="strips__strip"> <di...2015-11-24
  • jQuery 1.9使用$.support替代$.browser的使用方法

    jQuery 从 1.9 版开始,移除了 $.browser 和 $.browser.version , 取而代之的是 $.support 。 在更新的 2.0 版本中,将不再支持 IE 6/7/8。 以后,如果用户需要支持 IE 6/7/8,只能使用 jQuery 1.9。 如果要全面支持 IE,并混合...2014-05-31
  • jQuery+slidereveal实现的面板滑动侧边展出效果

    我们借助一款jQuery插件:slidereveal.js,可以使用它控制面板左右侧滑出与隐藏等效果,项目地址:https://github.com/nnattawat/slideReveal。如何使用首先在页面中加载jquery库文件和slidereveal.js插件。复制代码 代码如...2015-03-15
  • jquery validate demo 基础

    jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求。该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自...2015-10-30
  • jQuery 中的 DOM 操作

    在DOM操作中,常常需要动态创建HTML内容,使文档在浏览器里的呈现效果发生变化,并且达到各种各样的人机交互目的....2016-04-27
  • 使用JQuery实现Ctrl+Enter提交表单的方法

    有时候我们为了省事就操作键盘组合键去代替使用鼠标,我们今天就使用JQuery实现Ctrl+Enter提交表单。我们发帖时,在内容输入框中输入完内容后,可以点击“提交”按钮来发表内容。可是,如果你够“懒”,你可以不用动鼠标,只需按...2015-10-23