zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Implementing image lightbox functionality

One essential feature of writing a blog is the image lightbox functionality, which allows users to click and enlarge images. However, different blogging platforms use different plugins. Here, I have developed a set of lightbox plugins that can meet the requirements of most platforms. It has been tested with Hexo, Hugo, and Typecho, and works without any issues.

Importing Files#

First, we need to import two key files: zoom.css and zoom.js.

<!-- Head section -->
<link rel="stylesheet" href="https://cdn.imhan.cn/list/zoom.css">

<!-- Body section -->
<!-- If you already have the jQuery file, there is no need to import jQuery -->
<script src="https://cdn.imhan.cn/list/jquery3.6.0.js"></script> 
<!-- Image lightbox -->
<img src="" alt="" class="bigimg">
<div class="mask"></div>
<script src="https://cdn.imhan.cn/list/zoom.js"></script>

Since these files are hosted on my own server, I cannot guarantee that the paths will remain the same in the future. I recommend opening the browser and copying the code locally for use.

Calling JavaScript#

Next, we need to assign a class name to the images and a parent element box. You can also use jQuery to accomplish this.

Here, .post-content is the class name of the main content. If you have a different class name, you can directly replace .post-content.

$(function(){
	$('.post-content img').addClass('smallimg')
  	$('.post-content img').wrap('<div class="imgbox"></div>')

})

Then, we need to initialize the plugin. Add the following code below the previous code.

$(function(){
	$('.post-content img').addClass('smallimg')
		$('.post-content img').wrap('<div class="imgbox"></div>')

		/*
	smallimg   // Small image
	bigimg  // Image to be enlarged on click
	mask   // Black overlay
	*/
	var obj = new zoom('mask', 'bigimg', 'smallimg');
	obj.init();
})

Now, when you click on an image in the content, it will enlarge successfully.

Conclusion#

Let's try it out with a random image!

image

The reason I have restricted the enlargement to the content area is that there are also images in other parts of the website. Enlarging all images would be unreasonable.

If you encounter any issues while using this, please feel free to leave a comment.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.