You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.length is 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 left and right to $('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 onInit callback receives the Fancybox instance as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:35:19