【问题标题】:Change Iframe src based on user input根据用户输入更改 Iframe src
【发布时间】:2021-08-08 20:32:52
【问题描述】:

我似乎找不到任何有效的方法,但我需要一些 html 来根据输入到文本框中的 url 创建 iframe。我使用 iframe 来解锁学校 chromebook 上的网站,但如果我只想检查一个网站并通过创建一个全新的网站来查看它在 iframe 上的工作方式,那就很麻烦了。我只是想在 iframe 中轻松预览 URL。

【问题讨论】:

    标签: javascript html url iframe


    【解决方案1】:

    为了更改 iframe 源,您需要一个侦听器,用于监听输入何时更改,何时更改,请通过更新 src 属性来更改 iframe 的源。设置监听器,你可以这样做:

    // Grab the element by ID
    document.getElementById("example_input")
      // Add the event listener to "input" 
      .addEventListener("input", exampleFunc);
      
    function exampleFunc(event){
      // Grab iframe by ID
      let iframe = document.getElementById("example");
      // Update the source
      
      // First grab the input that was typed into
      let input = event.target;
      // Next get the value of that input
      let newUrl = input.value;
      
      // Now update the "src" property of the iframe
      iframe.src = newUrl;
    }
    <html>
    
    <head></head>
    
    <body>
      <input type="url" value="https://example.com" id="example_input">
      <iframe id="example" src="https://example.com" width="1000" height="450" frameborder="0" scrolling="no"></iframe>
    </body>
    
    </html>

    尽管在这种情况下,您可能不想在每次输入时都更新它,而是在用户停止输入时更新它,这在this question 中有解决方案。

    另请注意,由于各种原因(X-Frame-Options 标头、内容安全策略等),许多网站不允许 iframe 建立连接,例如 Google 和 YouTube 就是无法使用的网站。

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2014-04-11
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 2013-07-28
      相关资源
      最近更新 更多