如何在Fancybox 3的onInit()中获取缩略图当前数量
Solution for Fancybox v3: Check Thumbnail Count in onInit
Got it, let's sort this out for you! To reliably get the number of thumbnails (total items in the Fancybox group) within the onInit callback, you can use Fancybox's built-in instance properties instead of guessing. Here's the corrected and optimized code:
onInit: function(instance) { // Get total number of items (matches the thumbnail count) const totalThumbnails = instance.group.length; if (totalThumbnails > 4) { // Replace these with your actual custom elements (your original code used $('html') which is incorrect) const leftControl = $('<div class="fancyfunc left">Left Nav</div>'); const rightControl = $('<div class="fancyfunc right">Right Nav</div>'); setTimeout(function() { // Fixed selector: added dot to target the class instead of a non-existent tag $(".fancybox-container").append(leftControl).append(rightControl); }, 1); } }
Key Fixes & Explanations:
- Get Thumbnail Count Correctly:
instance.group.lengthis the official way to get the total number of items in the current Fancybox group, which directly maps to the number of thumbnails. No messy DOM queries needed here! - Fix Selector Typo: Your original code used
$("fancybox-container")— missing the dot (.) for class selection, so it was trying to target a non-existent HTML tag instead of the actual container class. - Correct Element Creation: You originally assigned
leftandrightto$('html'), which would append the entire HTML element to the Fancybox container (definitely not what you want). Replace those with your actual custom UI elements (like navigation controls) as shown. - Instance Reference: The
onInitcallback receives the Fancyboxinstanceas a parameter, which gives you access to all built-in properties and methods for full control over the gallery.
Bonus Tip:
If you specifically need to count only visible thumbnails (not total items in the group), you can query the thumbnail container directly:
const visibleThumbnails = $(".fancybox-thumbs__list").children().length;
But in most cases, instance.group.length is the more reliable and efficient way to get the total thumbnail count.
内容的提问来源于stack exchange,提问作者LordNeic
相关产品推荐
相关产品推荐

