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

如何为iframe中的游戏添加带game类的全屏切换功能?

实现iframe游戏的独立全屏功能

一、自定义代码实现

1. 修改后的HTML结构

给iframe添加game类和allowfullscreen属性,同时添加全屏触发按钮:

<div class="game-container">
  <iframe class="game" src="https://gameexample.com/" width="800" height="600" scrolling="none" frameborder="0" allowfullscreen></iframe>
  <button class="fullscreen-btn" title="全屏游戏">
    <i class="fa-solid fa-expand"></i>
  </button>
</div>

2. 按钮样式CSS

让按钮悬浮在iframe右上角,优化视觉和交互体验:

.game-container {
  position: relative;
  display: inline-block;
}

.fullscreen-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0,0,0,0.7);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  z-index: 10;
}

.fullscreen-btn:hover {
  background: rgba(0,0,0,0.9);
}

3. 全屏控制JavaScript

实现按钮点击切换iframe全屏状态,并同步图标切换:

const fullscreenBtn = document.querySelector('.fullscreen-btn');
const gameIframe = document.querySelector('.game');

// 点击按钮切换全屏(兼容多浏览器)
fullscreenBtn.addEventListener('click', () => {
  if (!document.fullscreenElement) {
    gameIframe.requestFullscreen?.() || 
    gameIframe.webkitRequestFullscreen?.() || 
    gameIframe.msRequestFullscreen?.();
    fullscreenBtn.querySelector('i').classList.replace('fa-expand', 'fa-compress');
  } else {
    document.exitFullscreen?.() || 
    document.webkitExitFullscreen?.() || 
    document.msExitFullscreen?.();
    fullscreenBtn.querySelector('i').classList.replace('fa-compress', 'fa-expand');
  }
});

// 监听全屏状态变化,自动同步图标
const updateIcon = () => {
  const isFullscreen = document.fullscreenElement === gameIframe ||
                       document.webkitFullscreenElement === gameIframe ||
                       document.msFullscreenElement === gameIframe;
  const icon = fullscreenBtn.querySelector('i');
  isFullscreen 
    ? icon.classList.replace('fa-expand', 'fa-compress') 
    : icon.classList.replace('fa-compress', 'fa-expand');
};

document.addEventListener('fullscreenchange', updateIcon);
document.addEventListener('webkitfullscreenchange', updateIcon);
document.addEventListener('msfullscreenchange', updateIcon);

注意事项

  • 确保已引入FontAwesome图标库(使用fa-expand和fa-compress图标),可通过本地资源或官方CDN加载。
  • allowfullscreen属性是iframe实现全屏的必要前提,不可省略。

二、WordPress插件推荐

以下插件可快速实现需求,无需手动编写代码:

  • Embed Plus:支持iframe全屏控制,可自定义触发按钮样式,兼容各类嵌入内容
  • Advanced iFrame:提供精细化全屏设置,可指定仅目标iframe进入全屏,支持按钮位置自定义
  • WP Fullscreen:专注元素级全屏功能,可针对带game类的iframe添加专属全屏按钮,配置灵活

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:35:29