[英]How to write html in js
我想写
<body>
<html>
<div id="myfilter" style="position:absolute;background-color:#000000;opacity:0.3;width:100%;height:100%;display:none">
</div>
<div id="myrestartbutton" style="display:none;position:absolute;color:white;padding:20px;padding-top:0;border-radius:10px; top: 50%;left: 50%;transform: translate(-50%, -50%);background:Black;">
<h1>Score:
<span id="score">
</span>
</h1>
<center>
<button id="btn" onclick="restartGame()">Restart
</button>
</center>
</div>
<div id="canvascontainer">
</div>
</html>
</body>
在仅使用 JS 文件的 html 中,我希望我的 html 文件如下所示:
<script src="index.js"></script>
我想要一种纯粹的 JS 方式来做到这一点。
您可以使用document.write
。
document.write('<body><html><div id="myfilter" style="position:absolute;background-color:#000000;opacity:0.3;width:100%;height:100%;display:none"></div><div id="myrestartbutton" style="display:none;position:absolute;color:white;padding:20px;padding-top:0;border-radius:10px; top: 50%;left: 50%;transform: translate(-50%, -50%);background:Black;"><h1>Score: <span id="score"></span></h1> <center><button id="btn" onclick="restartGame()">Restart</button></center></div><div id="canvascontainer"></div></html></body>')
这样做的正确方法不是上面建议的方法。 虽然它确实有效,但从技术上讲,有完整的框架可以帮助构建 HTML,客户端 Javascript 执行所有 DOM 操作。 因此,您可以以全新的方式将 JS 代码与 HTML 混合。
看看这个: https : //www.w3schools.com/react/react_jsx.asp
它具有 HTML 的所有感觉,但通过 JavaScript 运行时呈现。 关键是,您不必编写低级 JS 代码,而是将其外包给框架,将时间花在更大的更高级别的问题上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.