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

如何在Fancybox3的afterShow后聚焦iframe且不影响ESC关闭功能?

解决方案:聚焦iframe而非Fancybox实例,同时保留ESC关闭功能

问题的核心在于调用instance.focus()会把焦点转移到Fancybox的模态容器上,导致ESC键盘事件被容器拦截或无法传递到Fancybox的关闭逻辑。我们可以转而直接聚焦iframe元素,同时通过捕获阶段的键盘事件监听确保ESC键仍然能触发Fancybox关闭。

具体实现步骤如下:

  1. 在Fancybox的afterShow.fb事件中,定位当前slide对应的iframe元素
  2. 给iframe添加tabindex属性(确保它具备可聚焦能力)
  3. 直接聚焦iframe本身(而非Fancybox实例)
  4. 在主文档的捕获阶段添加ESC键监听,优先触发Fancybox关闭逻辑

修改后的完整代码如下:

<a data-fancybox data-type="iframe" href="https://e.issuu.com/embed.html?embedType=script&u=actes_sud&d=l_onard_anatomiste_liseuse&p=">Léonard de Vinci anatomiste</a>
$(document).on("afterShow.fb", function(e, instance, slide) {
  // 获取当前slide中的iframe元素
  const iframe = slide.$content.find('iframe')[0];
  
  if (iframe) {
    // 添加tabindex属性,让iframe可以被聚焦
    iframe.setAttribute('tabindex', '0');
    
    // 聚焦iframe,确保嵌入的电子书无需点击即可响应右键
    iframe.focus();
    
    // 在捕获阶段监听ESC键,确保优先触发关闭操作
    const handleEscape = function(event) {
      if (event.key === 'Escape') {
        instance.close();
        // 关闭后移除监听,避免内存泄漏
        document.removeEventListener('keydown', handleEscape, true);
      }
    };
    
    document.addEventListener('keydown', handleEscape, true);
  }
});

方案说明

  • 直接聚焦iframe:让嵌入的Issuu电子书内容处于激活状态,无需手动点击iframe或启动按钮即可响应右键操作
  • 捕获阶段监听ESC:键盘事件的捕获优先级高于冒泡,即使iframe获得焦点,ESC事件会先被主文档的监听到,从而触发Fancybox关闭
  • 移除监听:关闭Fancybox后及时移除ESC监听,避免对后续页面操作造成干扰

如果担心iframe加载延迟导致聚焦失效,可以加上onload事件确保内容就绪后再聚焦:

$(document).on("afterShow.fb", function(e, instance, slide) {
  const iframe = slide.$content.find('iframe')[0];
  
  if (iframe) {
    iframe.setAttribute('tabindex', '0');
    
    // 处理iframe加载完成的情况
    const focusIframe = () => iframe.focus();
    
    // 若iframe已加载完成(缓存状态),直接聚焦
    if (iframe.contentWindow?.document.readyState === 'complete') {
      focusIframe();
    } else {
      // 等待iframe加载完成后再聚焦
      iframe.onload = focusIframe;
    }
    
    // ESC监听逻辑
    const handleEscape = function(event) {
      if (event.key === 'Escape') {
        instance.close();
        document.removeEventListener('keydown', handleEscape, true);
      }
    };
    
    document.addEventListener('keydown', handleEscape, true);
  }
});

内容的提问来源于stack exchange,提问作者rpaul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:24:37