How to use JavaScript to achieve image lightbox effect?
How to use JavaScript to achieve the image lightbox effect?
With the development of social media and web design, the picture lightbox effect has become one of the common interactive special effects in many websites. Image lightbox is an effect that displays an enlarged image in the center of the screen by clicking on it. It not only improves the user experience, but also better displays the details of the image. In this article, we will learn how to use JavaScript to implement a simple image lightbox effect.
First, we need an HTML page to display images. Below is a basic HTML structure.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>图片灯箱</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <img class="lightbox lazy" src="/static/imghwm/default1.png" data-src="image1.jpg" alt="Image 1"> <img class="lightbox lazy" src="/static/imghwm/default1.png" data-src="image2.jpg" alt="Image 2"> <img class="lightbox lazy" src="/static/imghwm/default1.png" data-src="image3.jpg" alt="Image 3"> </div> <div id="lightbox" class="hidden"> <img src="/static/imghwm/default1.png" data-src="script.js" class="lazy" alt="Lightbox Image" id="lightbox-image"> <span id="close-button">X</span> </div> <script></script> </body> </html>
In the above code, we created a container containing three pictures and added a class of "lightbox" to each picture. We also create a hidden div to display the enlarged image, with the id "lightbox". In this div, we added an empty image and a close button.
Next, we need to create some CSS styles to achieve the effect of the image lightbox. Create a file named style.css and add the following styles:
.container { display: flex; } .lightbox { cursor: pointer; width: 200px; height: 200px; } #lightbox { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); display: flex; justify-content: center; align-items: center; flex-direction: column; text-align: center; z-index: 9999; } #lightbox img { width: 80%; max-height: 80%; margin-bottom: 20px; } #close-button { color: #fff; font-size: 30px; cursor: pointer; }
In the above CSS style, we set the style of the container and image so that they can be displayed in the form of a grid on the page . We also define a style called "lightbox" that is used to adjust the layout and background color when the image is enlarged. Finally, we set the style for the enlarged image and the style for the close button.
Now, we can start writing JavaScript code. Create a file named script.js in the same directory as the HTML file and add the following code:
// 获取所有的图片元素 var lightboxImages = document.getElementsByClassName("lightbox"); // 获取放大图片和关闭按钮元素 var lightbox = document.getElementById("lightbox"); var lightboxImage = document.getElementById("lightbox-image"); var closeButton = document.getElementById("close-button"); // 绑定点击事件,显示放大图片 for (var i = 0; i < lightboxImages.length; i++) { lightboxImages[i].addEventListener("click", function() { var imageSource = this.getAttribute("src"); lightboxImage.setAttribute("src", imageSource); lightbox.classList.remove("hidden"); }); } // 绑定点击事件,隐藏放大图片 closeButton.addEventListener("click", function() { lightbox.classList.add("hidden"); });
In the above JavaScript code, we first get all the files through the getElementsByClassName
method Image element with "lightbox" class. Next, we get the elements for the zoom image and the close button. Then, we use a loop to bind a click event to each image. When the user clicks on the image, the source address of the image is set to the address of the enlarged image, and the hidden style of the enlarged image is removed. Finally, we bind the click event of the close button and add a hidden style to enlarge the image when the user clicks the close button.
Now, we can open the HTML file in the browser, click on the image, and see the effect of the image being enlarged and displayed in the center of the page. When the close button is clicked, the enlarged image will be hidden.
The above is the sample code for using JavaScript to achieve the image lightbox effect. You can modify and expand it according to your needs to create more complex and diverse picture lightbox effects. I wish you success in achieving this!
The above is the detailed content of How to use JavaScript to achieve image lightbox effect?. For more information, please follow other related articles on the PHP Chinese website!

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
