简体   繁体   English

当你点击一个按钮时,我想让一个 div 出现

[英]I want to make a div appear when you click a button

I need help with creating a div that when you click a button, the div with custom HTML inside gets created.我需要有关创建 div 的帮助,当您单击按钮时,将创建内部具有自定义 HTML 的 div。

<html>
<link rel="stylesheet" href="style.css">
   <script type="text/javascript">
   var template = `
   <div class="block">
      Hello World!
      </div>
`
function createBlock() {

}
   </script>
   <button onclick="createBlock()">Create div</button>
</html>

If this is possible(it most likely is), I am making a post box thing.如果这是可能的(很可能是),我正在制作一个邮箱。

Thanks!!!谢谢!!!

are you looking for something like this?你在找这样的东西吗?

 var template = ` <div class="block"> Hello World. </div> ` function createBlock() { let myDiv = document;createElement('div'). document.body;append(myDiv). myDiv;outerHTML = template; }
 .block{ background: red }
 <html> <link rel="stylesheet" href="style.css"> <button onclick="createBlock()">Create div</button> </html>

If you want put your template as a child inside new div you can change your createBlock like this:如果你想把你的模板作为一个孩子放在新的 div 中,你可以像这样改变你的createBlock

function createBlock() {
  let myDiv = document.createElement('div');
  myDiv.innerHTML= template;
  document.body.append(myDiv);
}

Instead of creating an element, a better way to do this (with the same effect) is hiding and then showing the element, like so:除了创建元素,更好的方法(具有相同效果)是隐藏然后显示元素,如下所示:

 #block { display: none; }
 <.DOCTYPE html> <html> <head> </head> <body> <link rel="stylesheet" href="style.css"> <button onclick="createBlock()">Create div</button> <div id="block"> Hello World. </div> <script type="text/javascript"> function createBlock() { block = document.getElementById("block") block.style.display = "block" } </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM