jQuery implements magnifying glass effect_html/css_WEB-ITnose
Jun 24, 2016 pm 12:33 PM
1.1.1 Summary
I believe everyone has seen or used the magnifying glass effect, or even achieved it. It is generally used to magnify product pictures, and some e-commerce websites (such as: Fanke, JD.com) Mall, Alibaba, etc.) all have similar image viewing effects.
In the next blog post, we will introduce you to the magnifying glass effect through jQuery.
Directory implementation principle mousemove event relative coordinates background-position attribute mousewheel event 1.1.2 Text implementation principleFirst, let’s explain how to implement the magnifying glass effect:
Method 1: Prepare a high-pixel photo When the mouse is placed on the original image, the corresponding position of the large image will be loaded and displayed.
Method 2: Enlarge the original image, that is, adjust the length and width of the original image.
Above we introduced two methods to achieve the magnifying glass effect. Next, we apply the above two methods to our jQuery plug-in.
First of all, we need an img element to display the original image object, and a container as a display box; the large image object is stored in the display box. When the mouse moves over the original image, the corresponding part is displayed by absolute positioning of the large image, achieving a magnifying glass-like effect.
Next, let us define the Index.html page, the specific implementation is as follows:
<!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>
Above, we defined the small object to display the original image, and the large object as a display box Used to display the corresponding position of the large image.
mousemove eventNext, we use the jQuery plug-in to achieve the magnifying glass effect. When the mouse moves over the small object, the corresponding position of the large image will be displayed in the large object. This involves the mousemove event. , so we need to implement the listening method of the mousemove event (how to define the jQuery plug-in, please refer to "Customizing the jQuery Plug-in Step by Step").
Now, let’s implement the jquery.imagezoom.js plugin!
;(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 }); } } });});
Above, I implemented the listening method of the mousemove event. When the mouse moves to the magnify object, we need to get the relative coordinate position of the current mouse. Below we explain how to get the relative coordinate position of the mouse through pictures. .
Relative coordinates
Figure 1 Relative coordinate position of the mouse
When the mouse moves to the magnify object, we need to get the relative coordinate position of the mouse in the magnify object. Here we put the relative coordinate position of the mouse in the magnify object. The coordinates are defined as (mx, my). From the above figure, we know that the relative coordinates are equal to (pageX - offsetLeft, pageY - offsetTop).
Now, we have obtained the coordinate value of the mouse in the magnify object. Next, we need to obtain the corresponding coordinates of the corresponding large image. Here we define the corresponding coordinates of the large image as (rx, ry). We can Obtain the value of (rx, ry) through the proportional relationship.
mx / small.width (width of the original image) = rx / native_width (width of the large image)
my / small.height (length of the original image) = ry / native_height (large The length of the picture)
Through the above proportional relationship, we know that the coordinates (rx, ry) of the large picture are equal to (mx/small.width*native_width, my/small.height*native_height).
Through the above formula, we can obtain the corresponding coordinate position of the large image. When the mouse moves to the magnify object, the corresponding part of the large image will be displayed. Next, we need to implement the loading of the large image.
background-position attributeBefore implementing the loading and display of large images, first introduce the knowledge of background positioning background-position in CSS.
Figure 2 CSS background-position
Above, there is a 100x100 pixel image composed of four colors , and each color occupies 50 x 50 pixels. Next, we will display different positions of the image by modifying the background-position attribute value of the CSS of the image.
We see that there are two rows of small squares under the big square. They display different colors and positions. Here we achieve this by modifying the background-position attribute value of the CSS of each div element. of.
For example: for the blue square in the first row, we set the background-position property of CSS to: 0px -50px; this is equivalent to moving the original image up 50px, and the other squares in the first row are also moved up by left and right Implemented by moving up and down.
But the squares in the second row are even weirder, because they are composed of four colors, and the positions of the colors are different. How is this achieved?
For example: for the first square in the second row, we set the background-position property of CSS to: 25px 25px; this is equivalent to the original image moving down and to the right by 25px, due to the effect of image wrap. The color that will fill the remaining positions.
Now, we have understood the role of the background-position property of CSS, so we display the corresponding image part by modifying the background-position property of the large object. The specific implementation is as follows:
$large.css({ left: px, top: py, backgroundPosition: bgp});
Above, we achieved the magnifying glass effect by loading a large image. Next, we will introduce how to achieve the magnifying glass effect by adjusting the length and width of the original image.
mousewheel eventEarlier, we used the mousemove event to enlarge the image. Here we will use the mouse wheel event to achieve the image enlargement effect.
由于,不同的瀏覽器有不同的滾輪事件。主要是有三種:onmousewheel(IE 6/7/8)、mousewheel(IE9,Chrome,Safari和Opera)和DOMMouseScroll(只有Firefox支持),關(guān)于這三個(gè)事件這里不做詳細(xì)的介紹了。
由于不同瀏覽器之間存在著差異,為了實(shí)現(xiàn)瀏覽器之間的兼容,所以,我們需要監(jiān)聽以上三種滾輪事件(onmousewheel,mousewheel和DOMMouseScroll),具體實(shí)現(xiàn)如下:
$(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {});
上面,我們實(shí)現(xiàn)了兼容不同瀏覽器的滾輪事件監(jiān)聽方法,接下來(lái),判斷滾輪向上或向下也要考慮不同瀏覽器的兼容性,主流的覽器(IE、Opera、Safari、Firefox、Chrome)中Firefox 使用detail,其余四類使用wheelDelta;兩者只在取值上不一致,代表含義一致,detail與wheelDelta只各取兩個(gè)值,detail只取±3,wheelDelta只取±120,其中正數(shù)表示為向上,負(fù)數(shù)表示向下。
由于detail和wheelDelta都有兩個(gè)值表示向上或向下滾動(dòng),所以不同瀏覽器間可以通過(guò)以下方式實(shí)現(xiàn)兼容,具體實(shí)現(xiàn)如下:
$(".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)));});
上面,我們已經(jīng)處理了不同瀏覽器滾輪監(jiān)聽方法,當(dāng)用戶滾動(dòng)滾輪時(shí)需要?jiǎng)討B(tài)地修改原圖的尺寸,這里我們定義縮放比scaling為0.3,也就是說(shuō)每當(dāng)用戶滾動(dòng)一下滾輪原圖就按0.3的比例進(jìn)行縮放,具體實(shí)現(xiàn)如下:
// 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");
現(xiàn)在,我們已經(jīng)實(shí)現(xiàn)了通過(guò)滾輪對(duì)圖片進(jìn)行縮放查看的效果,完整的實(shí)現(xiàn)如下:
/************************************ 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 放大鏡效果
上面,我們實(shí)現(xiàn)了放大鏡效果,當(dāng)我們鼠標(biāo)停留在圖片上方會(huì)自動(dòng)放大圖片的相應(yīng)部位,當(dāng)然我們可以通過(guò)滾輪調(diào)整放大的比例。
1.1.3 總結(jié)在本博文中,我們介紹了如何實(shí)現(xiàn)放大鏡效果,總的來(lái)說(shuō),我們可以通過(guò)兩種方式實(shí)現(xiàn)放大鏡效果,而且在博文中都給出了詳細(xì)的介紹,通過(guò)mousemove事件實(shí)現(xiàn)加載大圖的效果,mousewheel事件實(shí)現(xiàn)動(dòng)態(tài)修改原圖的尺寸。
這只是一個(gè)簡(jiǎn)單的程序,我們還有很大的改善空間,提供一個(gè)內(nèi)容豐富和功能強(qiáng)大的程序是我們的目標(biāo)。
參考 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-css3Demo

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ARIA's role attribute is used to define the role of web elements and improve accessibility. 1. Role attribute helps assistive technology to understand the functions of elements, such as buttons, navigation, etc. 2. Use role attributes to assign specific roles to non-semantic HTML elements. 3. The role attribute should be consistent with the element behavior and be verified by the accessibility tool test.

How to create a website layout? 1. Use HTML tags to define the content structure, such as, ,. 2. Control styles and positions through CSS, using box model, float or Flexbox layout. 3. Optimize performance, reduce HTTP requests, use cache and optimize images, and ensure responsive design.

Improve the readability and maintainability of HTML code can be achieved through the following steps: 1. Use semantic tags, such as, etc. to make the code structure clear and improve SEO effect; 2. Keep the code formatted and use consistent indentation and spaces; 3. Add appropriate comments to explain the code intention; 4. Avoid excessive nesting and simplify the structure; 5. Use external style sheets and scripts to keep the HTML concise.

The key to keep up with HTML standards and best practices is to do it intentionally rather than follow it blindly. First, follow the summary or update logs of official sources such as WHATWG and W3C, understand new tags (such as) and attributes, and use them as references to solve difficult problems; second, subscribe to trusted web development newsletters and blogs, spend 10-15 minutes a week to browse updates, focus on actual use cases rather than just collecting articles; second, use developer tools and linters such as HTMLHint to optimize the code structure through instant feedback; finally, interact with the developer community, share experiences and learn other people's practical skills, so as to continuously improve HTML skills.

The reason for using tags is to improve the semantic structure and accessibility of web pages, make it easier for screen readers and search engines to understand page content, and allow users to quickly jump to core content. Here are the key points: 1. Each page should contain only one element; 2. It should not include content that is repeated across pages (such as sidebars or footers); 3. It can be used in conjunction with ARIA properties to enhance accessibility. Usually located after and before, it is used to wrap unique page content, such as articles, forms or product details, and should be avoided in, or in; to improve accessibility, aria-labeledby or aria-label can be used to clearly identify parts.

To create a basic HTML document, you first need to understand its basic structure and write code in a standard format. 1. Use the declaration document type at the beginning; 2. Use the tag to wrap the entire content; 3. Include and two main parts in it, which are used to store metadata such as titles, style sheet links, etc., and include user-visible content such as titles, paragraphs, pictures and links; 4. Save the file in .html format and open the viewing effect in the browser; 5. Then you can gradually add more elements to enrich the page content. Follow these steps to quickly build a basic web page.

HTMLtagsareessentialforstructuringwebpages.Theydefinecontentandlayoutusinganglebrackets,ofteninpairslikeand,withsomebeingself-closinglike.HTMLtagsarecrucialforcreatingstructured,accessible,andSEO-friendlywebpages.

To create an HTML checkbox, use the type attribute to set the element of the checkbox. 1. The basic structure includes id, name and label tags to ensure that clicking text can switch options; 2. Multiple related check boxes should use the same name but different values, and wrap them with fieldset to improve accessibility; 3. Hide native controls when customizing styles and use CSS to design alternative elements while maintaining the complete functions; 4. Ensure availability, pair labels, support keyboard navigation, and avoid relying on only visual prompts. The above steps can help developers correctly implement checkbox components that have both functional and aesthetics.
