在iframe中,通过点击按钮从输入字段加载网页

时间:2019-07-11 07:57:57

标签: javascript html css iframe

我想在输入字段中从用户获取URL。然后,当用户单击“加载”按钮时,我想在iframe中加载该网址。到目前为止,这是我尝试在iframe中加载网址但失败的方法。请帮忙 !我是HTMl和Web知识的首次用户。

function myFunction() {
  var x = document.getElementById("ur").value;
  document.getElementById("demo").innerHTML = x;

}
<h3>Enter the URl in input field</h3>

<p>Click the button to get the url displayed in the iframe.</p>



<form>
  Enter the URL: <input id="ur" type="text" name="url"><br>
  <input type="button" id="myBtn" onclick="myFunction()" value="Load">
</form>


<p id="demo"></p>

2 个答案:

答案 0 :(得分:0)

像这样设置iframe src

function myFunction() {
  var x = document.getElementById("ur").value;
  document.getElementById("demo").innerHTML = x;
  document.getElementById('myIframe').src = x;
}
<h3>Enter the URl in input field</h3>

<p>Click the button to get the url displayed in the iframe.</p>

<form>
  Enter the URL: <input id="ur" type="text" name="url"><br>
  <input type="button" id="myBtn" onclick="myFunction()" value="Load">
</form>

<iframe id="myIframe" src="https://stackoverflow.com" width="500" height="200"></iframe>

<p id="demo"></p>

请注意,您无法在iframe中看到很多网站,因为这些网站将X-Frame-Options设置为拒绝!

答案 1 :(得分:0)

将功能更新为此。使用javascript的createElement创建并附加到正文中。您可以将其更改为在其他任何元素之后追加。

function myFunction() {
  var x = document.getElementById("ur").value;
  var ifrm = document.createElement("iframe");
  ifrm.setAttribute("src", x);
  ifrm.style.width = "640px";
  ifrm.style.height = "480px";
  document.body.appendChild(ifrm);
}
相关问题