javascript - 如何将按钮放置在 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>
解决方案
像这样
您需要定位按钮并在加载时将其隐藏
我将它放在与 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>
推荐阅读
- android - 用另一个组件替换了一个组件,构建失败并出现错误“无法解析项目
" - javascript - JS 创建一个具有唯一随机数的数组
- c++ - 最接近值的二进制搜索向量 C++
- html - 响应式网页设计无法正确调整按钮大小
- c# - 创建 RawDiskLibrary 对象时磁盘名称无效
- node.js - “无效的论点”:我错过了什么吗?
- php - 如何在 PHP 的 array_reverse() 函数中使用 echo
- javascript - 如何将此代码转换为一个函数 jquery
- javascript - 在简单的登录表单中单击按 Enter 键
- laravel - 为什么不捕获我在 Laravel 5.7 中定义的路由请求的文件 URI?