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

求助:使用window.addEventListener结合JS媒体查询加载iframe失败

问题:仅在窗口宽度小于700px时加载指定iframe失败

我尝试用JavaScript媒体查询实现仅当窗口宽度小于700px时加载指定iframe,但两种写法都未成功:

第一种写法及问题

JS代码

mobile();
function mobile(){
    const mql = window.matchMedia('screen and (max-width: 700px)');
    checkMedia(mql);
    mql.addListener(checkMedia);
    function checkMedia(mql){
        if(mql.matches){
          function frameloading() {
              var frameone= document.getElementById("delayedframe");
              frameone.src = "360°-image url"
          };
          window.addEventListener("load",(frameloading));
        }
    }
}

对应HTML

<iframe id="delayedframe" src="about:blank" frameborder="0" style="position:absolute;top:100px;left:0px;right:0px;bottom:0px" height="200px" width="100%"><p>Your browser does not support iframes.</p></iframe>

错误点

  1. 绑定window.load事件时机错误:若页面已加载完成,该事件不会再次触发,导致iframe永远无法加载。
  2. 每次媒体查询匹配时重复绑定load事件,可能引发重复加载问题。

第二种写法及问题

JS代码

function checkMediaQuery() {
  if (window.innerWidth > 700) {
    function frameloading() {
        var frameone= document.getElementById("delayedframe");
        frameone.src = "360°-image url"
    };
    window.addEventListener("load",(frameloading));
  }
}
window.addEventListener('resize', checkMediaQuery);

对应HTML

<iframe id="delayedframe" src="about:blank" frameborder="0" style="position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%" class="forcewide"><p>Your browser does not support iframes.</p></iframe>

错误点

  1. 条件逻辑写反:需求是宽度小于700px时加载,代码中判断window.innerWidth > 700,完全不符合需求。
  2. 同样依赖window.load事件,页面加载完成后resize时无法触发加载。
  3. 未在页面初始化时执行检查,初始宽度小于700px时不会加载iframe。

正确实现方案

核心逻辑

  • 页面初始化时立即检查窗口宽度,符合条件则加载iframe。
  • 监听窗口resize事件,实时检查宽度变化。
  • 避免重复设置iframe的src,防止不必要的重复加载。

完整代码

JS代码

const iframe = document.getElementById('delayedframe');
const targetSrc = '360°-image url'; // 替换为你的实际URL

function loadIframeOnMobile() {
  const isMobile = window.matchMedia('screen and (max-width: 700px)').matches;
  // 仅当符合条件且src未设置时才加载
  if (isMobile && iframe.src !== targetSrc) {
    iframe.src = targetSrc;
  } else if (!isMobile && iframe.src !== 'about:blank') {
    // 可选:宽度大于700px时重置为空白
    iframe.src = 'about:blank';
  }
}

// 初始化检查
loadIframeOnMobile();
// 监听resize事件
window.addEventListener('resize', loadIframeOnMobile);

HTML代码

<iframe id="delayedframe" src="about:blank" frameborder="0" style="position:absolute;top:100px;left:0;right:0;bottom:0; height:200px; width:100%" ><p>Your browser does not support iframes.</p></iframe>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:52:56