ホームページ  >  記事  >  ウェブフロントエンド  >  jQuery で虫眼鏡効果を実装_html/css_WEB-ITnose

jQuery で虫眼鏡効果を実装_html/css_WEB-ITnose

WBOY
WBOYオリジナル
2016-06-24 12:33:39842ブラウズ

1.1.1 概要

誰もが虫眼鏡効果を見たり使用したり、実際にそれを実現したりしたことがあると思います。これは通常、製品の写真や一部の電子商取引 Web サイト (Fanke、Jingdong Mall など) を表示するために使用されます。 、Alibaba など)どれも同様の画像閲覧効果を持っています。

次のブログ投稿では、jQuery を使用した虫眼鏡効果を紹介します。

ディレクトリの実装原理、mousemove イベント、相対座標、background-position 属性、mousewheel イベント 1.1.2 テキストの実装原理

まず、虫眼鏡効果の実装方法を説明します。配置 元の画像上に、対応する位置に大きい画像を読み込んで表示します。

方法 2: 元の画像を拡大します。つまり、元の画像の長さと幅を調整します。

上記では、虫眼鏡効果を実現する 2 つの方法を紹介しました。次に、上記の 2 つの方法を 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>

上記では、元の画像を表示する小さなオブジェクトと、元の画像の対応する位置を表示する表示ボックスとして大きなオブジェクトを定義しました。大きな画像。

Mousemove イベント

次に、jQuery プラグインを使用して、マウスが小さなオブジェクト上を移動すると、大きな画像の対応する位置が大きなオブジェクトに表示されます。そのため、mousemoveイベントの監視メソッドを実装する必要があります(jQueryプラグインの定義方法については、「jQueryプラグインのステップバイステップのカスタマイズ」を参照してください)。

それでは、jquery.imagezoom.js プラグインを実装してみましょう。

rreee

上記では、マウスが拡大オブジェクトに移動したときに、現在のマウスの相対座標位置を取得する方法を図で説明します。 。

相対座標

図 1 マウスの相対座標位置

マウスが拡大オブジェクトに移動するとき、拡大におけるマウスの相対座標位置を取得する必要があります。ここでは相対座標を (mx, my. )、上の図から、相対座標が (pageX - offsetLeft、pageY - offsetTop) に等しいことがわかります。

さて、拡大オブジェクト内のマウスの座標値を取得しました。次に、大きな画像の対応する座標を取得する必要があります。ここでは、大きな画像の対応する座標を (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) に等しいことがわかります。

上記の式を通じて、大きな画像の対応する座標位置を取得できます。マウスが拡大オブジェクトに移動すると、大きな画像の対応する部分が表示されます。次に、大きな画像の読み込みを実装する必要があります。画像。

background-position プロパティ

大きな画像の読み込みと表示を実装する前に、まず CSS での背景の配置に関する知識を紹介します。

図 2 CSS の背景位置

上には 4 つの色で構成される 100x100 ピクセルの画像があり、各色は 50 x 50 ピクセルを占めます。次に、画像の CSS の背景位置を変更します。属性値は、画像のさまざまな位置を表示するために使用されます。

大きな正方形の下に 2 つの小さな正方形があり、異なる色と位置が表示されていることがわかります。ここでは、各 div 要素の CSS のbackground-position 属性値を変更することでこれを実現しています。

例: 最初の行の青い正方形の場合、CSS の背景位置プロパティを 0px -50px に設定します。これは、元の画像を 50 ピクセル上に移動することと同じです。最初の行の他の正方形も移動されます。左右と上下。

しかし、2 行目の正方形はさらに奇妙です。4 つの色で構成されており、色の位置が異なっています。これはどのようにして実現されるのでしょうか。

例: 2 行目の最初の正方形では、CSS の背景位置プロパティを 25px 25px に設定します。これは、元の画像が下と右に 25px 移動することに相当し、残りの画像が埋められます。画像のラップの色の影響による位置。

CSS のbackground-positionプロパティの役割を理解したので、対応する画像部分を表示するためにラージオブジェクトのbackground-positionプロパティを変更します。具体的な実装は次のとおりです。拡大鏡効果を実現する方法 次に、元の画像の長さと幅を調整して拡大鏡効果を実現する方法を紹介します。

マウスホイール イベント

先ほどは、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");

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

/************************************ Author: Jackson Huang* Blog: http://www.cnblogs.com/rush* Date: 8/23/2013* Reference:* http://www.sitepoint.com/html5-javascript-mouse-wheel/* http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3***********************************/;(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);

 

图3 放大镜效果

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

1.1.3 总结

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

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

参考 http://tech.pro/tutorial/681/css-tutorial-the-background-position-property http://www.sitepoint.com/html5-javascript-mouse-wheel/ http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3

Demo

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。