


Panzoom Image Scaling: Solve the problem of repeated triggering of click events
This document aims to solve the problem that the click event is repeatedly triggered when using the Panzoom library to implement the image click zoom function, causing the scaling failure. By analyzing the problem code, we will provide a more concise and effective solution that ensures that the image can be zoomed in and out in multiple steps as expected.
When using the Panzoom library, if you want to achieve the zoom function by clicking on the image itself, you may encounter a problem: the first click is valid, and the subsequent clicks are abnormal. This is usually caused by repeated binding of event listeners. The causes and solutions of the problem are described in detail below.
Problem analysis
The original code attempts to dynamically add a new click event listener after the first click to achieve the zoom-out function. However, this method will cause multiple click event listeners to exist simultaneously and interfere with each other. When the image is scaled to a maximum multiple, the zoom-in and zoom-out operations are triggered at the same time, resulting in confusing scaling behavior.
Solution
To solve this problem, dynamic addition of event listeners should be avoided, but instead handle both zoom in and out in the same event listener. By judging the current scaling ratio (panzoom.getScale()), we decide whether to perform the zoom in or out operation.
The following is the modified code:
let img = document.querySelector('img'); let panzoom = new Panzoom(img.parentElement, { minScale: 1, maxScale: 2.5, step: 0.5, panOnlyWhenZoomed: 1, cursor: 'zoom-in', }); img.addEventListener('click', () => { if (panzoom.getScale() <p> <strong>Code explanation</strong></p><ol> <li> <strong>Single event listener:</strong> Only one addEventListener is used to listen for click events of img element.</li> <li> <strong>Conditional judgment:</strong> In the click event handling function, use if (panzoom.getScale() </li> <li> <strong>Zoom in/out logic:</strong><ul> <li> If the scaling ratio is less than the maximum value (2.5), perform panzoom.zoomIn() to perform the zoom operation.</li> <li> Otherwise, execute panzoom.zoomOut() to perform the zoom-out operation.</li> </ul> </li> <li> <strong>Mouse style switching:</strong> Dynamically modify the mouse style according to the current zoom state to provide a better user experience.</li> </ol><p> <strong>Complete HTML example</strong></p><pre class="brush:php;toolbar:false"> <title>Panzoom Image Zoom</title> <style> html, body { height: 100%; width: 100%; } .offerBox_image { max-width: 429px; } .offerBox_image img { width: 100%; height: auto; margin: 0; padding: 0; } </style> <div class="offerBox_image"> <img class="img lazy" src="/static/imghw/default1.png" data-src="https://source.unsplash.com/random/1100x1100" data-id="1" alt=""> </div> <script src="https://unpkg.com/@panzoom/<a%20class=" __cf_email__ data-cfemail="f5c5d4dbcfdadad8b5819b809b85">[email protected]/dist/panzoom.min.js"></script> <script> let img = document.querySelector('img'); let panzoom = new Panzoom(img.parentElement, { minScale: 1, maxScale: 2.5, step: 0.5, panOnlyWhenZoomed: 1, cursor: 'zoom-in', }); img.addEventListener('click', () => { if (panzoom.getScale() < 2.5) { panzoom.zoomIn({ animate: true, step: 0.4 }); console.log("Zoom in: ", panzoom.getScale()); img.style.cursor = 'zoom-out'; } else { panzoom.zoomOut({ step: 1 }); img.style.cursor = 'zoom-in'; console.log("Zoom out: ", panzoom.getScale()); } }); </script>
Things to note
- step parameter: step parameter controls the amplitude of each scaling. Adjust the step values in the zoomIn and zoomOut methods according to actual needs.
- minScale and maxScale parameters: Make sure that the values of minScale and maxScale are set reasonably to avoid scaling out of range.
- CSS Style: Adjust the CSS style according to the actual page layout to ensure that the image container and image itself have the appropriate size.
Summarize
By avoiding repeated binding of event listeners and determining whether to perform zoom in or out based on the scaling scale in a single event listener, the problem of failure of Panzoom image click zoom can be effectively solved. This method not only has a cleaner code, but also has clearer logic and is easy to maintain.
The above is the detailed content of Panzoom Image Scaling: Solve the problem of repeated triggering of click events. For more information, please follow other related articles on the PHP Chinese website!

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.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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)

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

When using Bootstrap for web page layout, developers often encounter the problem of elements being displayed side by side rather than stacked vertically by default, especially when the parent container applies Flexbox layout. This article will explore this common layout challenge in depth and provide a solution: by adjusting the flex-direction attribute of the Flex container to column, using Bootstrap's flex-column tool class to achieve the correct vertical arrangement of H1 tags and content blocks such as forms, ensuring that the page structure meets expectations.
