首页 > 解决方案 > 单击时应显示 div 元素

问题描述

我想要一个div元素,我点击它。div然后应该弹出另一个元素。我尝试了一些东西,但不知道为什么它不起作用。

<div class="div" onclick="myFunction()">
  <img class="image" src="..." height="80px" width="80px">
  <h2 class="header">text</h2>
  <img class="more" src="..." height="50px" width="50px">
  </div>
  <script>
  function myFunction() {
  document.getElementById('text')
  [0].classList.toggle('display')
  <div class="news" onclick="myFunction()">
  <img class="coronanewsimg" src="https://www.mediothek-krefeld.de/files/content-fotos/Bilder%20fuer%20Neuigkeiten%20und%20Slider/628px-Achtung.svg.png" height="80px" width="80px">
  <h2 class="coronanewshead">Sonderschließzeit bis vorraussichtlich 07.03.21 aufgrund des Coronavirus</h2>
  <img class="mehr-pfeil" src="pics/mehr-pfeil.png" height="50px" width="50px">
  </div>
  <script>
  function myFunction() {
  document.getElementById('coronanewstext')
  [0].classList.toggle('display')
  }
  </script>
  <div class="text">
text
</div>

标签: javascripthtmlcssfunction

解决方案


div您还可以使用此方法在事件发生时创建元素。

<!DOCTYPE html>
<html>
 <head>
  <title>Event handling</title>
 </head>
 <body>
  <p>Click the button to pop up another div element.</p>
  <button onclick="popDiv()">Click me</button>
 <script>
  function popDiv() {
  var division = document.createElement("div");
  division.innerText = "This is a new DIV element";
  division.style.color = "blue";
  division.style.margin = "10px";           //Simple styling of div
  division.style.background = "whitesmoke";
  division.style.border = "1px solid black";
  document.body.appendChild(division);
  }
 </script>
 </body>
</html> 

在代码中打开和关闭标签时也要更正,否则这也可能导致错误。


推荐阅读