Use la combinación de appendChild y matriz para crear múltiples efectos de elementos o mostrar información de puntos en la imagen

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      width: 300px;
      height: 300px;
      border: 1px solid red;
      margin: 100px auto;
      position: relative;
      overflow: hidden;
    }

    .point {
      /* 解决鼠标点击圆点不在鼠标指向的地方,这是因为存在margin */
      margin: 0 0;
      width: 5px;
      height: 5px;
      border-radius: 50%;
      background-color: red;
      position: absolute;
    }
  </style>
</head>

<body>
 //如果是一个图片,以下内容正常定义,只需要把box.appendChild(p)改为box.parentNode.appendChild(p)就行了;
  <div id="box"></div>
  <script>
    var box = document.getElementById("box");
    // 定义一个数组变量
    var arr = [];
    box.addEventListener("click", function (event) {
      var p = document.createElement("p");
      p.className = "point";
      p.style.left = event.pageX - box.offsetLeft + "px";
      p.style.top = event.pageY - box.offsetTop + "px";
      box.appendChild(p);
      // 将圆点push到数组里去,因为数组属于引用类型,故能达到创建多个圆点
      arr.push(p);
    });
  </script>
</body>

</html>

Representaciones:

Supongo que te gusta

Origin blog.csdn.net/qq_72760247/article/details/129904513
Recomendado
Clasificación