我试图在单击按钮时显示 iframe。我得到了以下 JS 代码:
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = 'block';
}
这是我页面的 HTML:
<!DOCTYPE html PUBLIC>
<html>
<head>
<title>Welcome</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="global.css"/>
<link rel="stylesheet" type="text/css" href="buttons.css"/>
<link rel="stylesheet" type="text/css" href="paragraphs.css"/>
<link rel="stylesheet" type="text/css" href="iframes.css"/>
<script type="text/javascript" src="files.js"></script>
</head>
<body>
<form> <button id="files" onclick="show()">Files</button> </form>
<iframe id="iframe" src="files.html" width="200" height="100"></iframe>
</body>
</html>
脚本位于名为 files.js 的外部文件中。当我测试代码时,它可以工作,但 iframe 只显示 1 毫秒。怎么了?
预先感谢您的回答!
最佳答案
添加type="button"
给你的<button>
.就像现在一样,它在一个表单中,没有任何类型属性——这样它默认类型为 submit
。 ,因此当您单击它时,页面将被提交并消失。
另外,更改 onclick="show()"
至 onclick="show"
,或者更好——使用 .addEventListener()
相反。
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = 'block';
}
<!DOCTYPE html PUBLIC>
<html>
<head>
<title>Welcome</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="global.css"/>
<link rel="stylesheet" type="text/css" href="buttons.css"/>
<link rel="stylesheet" type="text/css" href="paragraphs.css"/>
<link rel="stylesheet" type="text/css" href="iframes.css"/>
<script type="text/javascript" src="files.js"></script>
</head>
<body>
<form> <button type="button" id="files" onclick="show">Files</button> </form>
<iframe id="iframe" src="files.html" width="200" height="100"></iframe>
</body>
</html>
编辑:响应 OP 评论的附加代码:
var iframeShowing = false;
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = iframeShowing ? 'block' : 'none';
iframeShowing = !iframeShowing;
}
关于javascript - 如何通过单击按钮显示 iframe (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513981/