【发布时间】:2011-01-07 17:29:13
【问题描述】:
如何在 JavaScript 中打开一个新窗口并插入 HTML 数据,而不仅仅是链接到一个 HTML 文件?
【问题讨论】:
标签: javascript html insert
如何在 JavaScript 中打开一个新窗口并插入 HTML 数据,而不仅仅是链接到一个 HTML 文件?
【问题讨论】:
标签: javascript html insert
我不建议您像其他人建议的那样使用document.write,因为如果您打开此类窗口两次,您的 HTML 将被复制两次(或更多)。
改用innerHTML
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
【讨论】:
var win = window.open("", "Page Help", "newwindow", "width=1100, height=700, top=100, left=100"); win.document.body.innerHTML = "help_text"; 但是窗口是全屏的,没有标题。为什么它不尊重我的设置?
您可以使用window.open在javascript中打开一个新窗口/标签(根据浏览器设置)。
通过使用 document.write,您可以将 HTML 内容写入打开的窗口。
【讨论】:
write() 之后也调用document.close(),以防您嵌入了JS 事件处理程序,因为这将触发DOMContentLoad 事件。
当您使用open 创建新窗口时,它会返回对新窗口的引用,您可以使用该引用通过其document 对象写入新打开的窗口。
这是一个例子:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
【讨论】:
以下是使用 HTML Blob 的方法,以便您可以控制整个 HTML 文档:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
这是代码,但 StackOverflow 阻止打开窗口(请参阅 codepen 示例):
const winHtml = `<!DOCTYPE html>
<html>
<head>
<title>Window with Blob</title>
</head>
<body>
<h1>Hello from the new window!</h1>
</body>
</html>`;
const winUrl = URL.createObjectURL(
new Blob([winHtml], { type: "text/html" })
);
const win = window.open(
winUrl,
"win",
`width=800,height=400,screenX=200,screenY=200`
);
【讨论】:
<head> 中包含 <meta charset="utf-8">,以确保它能够呈现任何非拉丁字符。
您可以通过以下代码打开一个新的弹出窗口:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
之后,您可以使用 myWindow.document.write(); 或 myWindow.document.body.innerHTML = "HTML"; 添加 HTML
我建议你首先创建一个任意名称的新 html 文件。 在这个例子中,我使用的是
newFile.html
并确保在该文件中添加所有内容,例如 bootstrap cdn 或 jquery,即所有链接和脚本。然后用一些 id 制作一个 div 或使用你的身体并给它一个id。在此示例中,我将 id="mainBody" 赋予了我的 newFile.html <body> 标记
<body id="mainBody">
然后使用
打开这个文件<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
然后在你的 body 标签中添加你想要添加的任何内容。使用以下代码
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
就这么简单。
【讨论】:
您还可以创建一个包含所需 html 的“example.html”页面,并将该页面的 url 作为参数提供给 window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");
【讨论】: