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, import our two key files, zoom.css
and zoom.js
.
<!-- Head section -->
<link rel="stylesheet" href="https://cdn.imhan.cn/list/zoom.css">
<!-- Bottom of the body section -->
<!-- If you already have the jQuery file, do not import it again -->
<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 the path in the future. I recommend opening it in a 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!
I have restricted the ability to enlarge images only within the content because there are images in other parts of the website as well. Enabling enlargement for all images would be unreasonable.
If you encounter any issues while using it, please feel free to leave a comment.