【问题标题】:Why won't my iframes load in this piece of code?为什么我的 iframe 无法加载到这段代码中?
【发布时间】:2022-11-23 21:22:02
【问题描述】:

所以我这里有一些代码可以检测它是移动浏览器还是桌面浏览器。这行得通,但我正在尝试根据浏览器提供不同的 iframe,但 iframe 未加载。请帮助/修复!


<html>
<body>
    <script>
        /* Storing user's device details in a variable*/
        let details = navigator.userAgent;
  
        /* Creating a regular expression 
        containing some mobile devices keywords 
        to search it in details string*/
        let regexp = /android|iphone|kindle|ipad/i;
  
        /* Using test() method to search regexp in details
        it returns boolean value*/
        let isMobileDevice = regexp.test(details);
  
        if (isMobileDevice) {
            document.write("You are using a Mobile Device");
        } else {
<iframe target="_parent" src="https://google.com/" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>
        }
    </script>
</body>
</html>

我尝试了 PHP 版本,但没有成功。请帮忙!

【问题讨论】:

  • 您已将 iFrame 的 html 标记包含在 javascript 中。您需要通过 document.createElement()innerHTML 在 JS 中构建它,或者您可以将它隐藏在您的 html 中并使用 JS 来显示它。

标签: javascript html


【解决方案1】:

这是解决方案,如果设备检测到用户代理是否移动将抛出不兼容的设备消息,否则将继续浏览器活动,即使他们在移动浏览器中启用桌面模式,仍然存在不兼容的消息

<html>
<head>
<style type="text/css">
    body {
        margin: 0 auto;
        padding: 0;
    }

    #root {
        display: grid;
        justify-content: center;
        align-items: center;
        width: 100vw;
        height: 100vh;
    }

    #browser {
        border: 0;
        width: inherit;
        height: inherit;
    }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/javascript">
    let device = navigator.userAgent;
    let isMobile = device.includes("Android") || device.includes("iPhone") || device.includes("iPad");
    let root = document.querySelector("#root");

    let message = () => {
        let p = document.createElement("p");
        p.textContent = "You are using a mobile device.";
        root.appendChild(p);
    };

    let browser = () => {
        let browser = document.createElement("iframe");
        browser.id = "browser";
        browser.target = "_parent";
        browser.src = "https://bing.com";
        browser.crossOrigin = "anonymous";
        root.appendChild(browser);
    }

    if (isMobile) {
        message();
    } else {
        browser();
    }
</script>
</body>
</html>

您可以使用三元运算符替代 IF ELSE 语句。

isMobile ? message() : browser();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多