首页 > 解决方案 > 如何将按钮放置在 Iframe 的中间并仅在按下后加载 Iframe?

问题描述

我创建了以下测试代码,其中创建了一个 Iframe 和一个按钮,并使用 jquery,仅在按下按钮后才加载 Iframe 的内容。

代码可以在以下位置运行:https ://www.w3schools.com/code/tryit.asp?filename=GE2BVI7NSQ7N

但是,现在按钮位于 iframe 下方,按下它后,它仍然存在。

我想要的是让按钮在 Iframe 内居中,有点像“加载此内容”按钮,在按下按钮后,它就会消失。

基本上,我想要的正是 Itch.io 正在做的事情,比如在这个页面上:https ://brackeysgames.itch.io/party-killer 。Iframe 中有一个应用程序和一个用于加载应用程序的按钮。一旦按钮被按下,它就会被移除并加载应用程序。

我怎么能做到这一点?

$("button").click(function() {
  var iframe = $("#myiFrame");
  iframe.attr("src", iframe.data("src"));
});
.iframe-container {
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

button {
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

h1 {
  margin: 0 auto;
  display: flex;
  justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1>Iframe test</h1>

<div class="iframe-container">
  <iframe id="myiFrame" data-src="https://www.w3schools.com" src="about:blank"></iframe>
</div>

<button type="button">Load Iframe</button>

标签: javascripthtmljquerycss

解决方案


像这样

您需要定位按钮并在加载时将其隐藏

我将它放在与 iframe 相同的容器中,并使其位置为绝对

$("button").click(function() {
  const $iframe = $("#myiFrame");
  const $but = $(this);
  $iframe.on("load",function() {
    $but.hide();
  })
  $iframe.attr("src", $iframe.data("src"));
});
.iframe-container {
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

button {
  margin: 0 auto;
  display: block;
  position:absolute;
  top:40%;
  left:45%; /* perhaps use calc here */
  justify-content: center;
  z-index:999;
}

h1 {
  margin: 0 auto;
  display: flex;
  justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1>Iframe test</h1>

<div class="iframe-container">
  <iframe id="myiFrame" data-src="https://www.w3schools.com" src="about:blank"></iframe>
  <button type="button">Load Iframe</button>
</div>


推荐阅读