如何读出元素在Javascript中的位置?

How can I read out the position of element in Javascript?

我正在尝试在 JavaScript 中编写一个小任务,人们可以在其中将两个对象拖放到屏幕上。这里是网站:http://www.unisg.bplaced.net/JS/dragdrop.html

我现在的目标是读出两个对象的结束位置。我想我并没有真正得到我想要读出的元素的名称。我尝试了以下内容。点击按钮后,我只得到"null"。

谢谢!

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
  <title>Drag Multiple Elements</title>
  <style>
    #container {
      width: 100%;
      height: 400px;
      background-image: url('http://www.unisg.bplaced.net/park.png');
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 7px;
      touch-action: none;
    }

    .item {
      border-radius: 50%;
      touch-action: none;
      user-select: none;
      position: relative;
    }

    .one {
      width: 50px;
      height: 50px;
      background-color: rgb(245, 230, 99);
      border: 10px solid rgba(136, 136, 136, .5);
      top: 40%;
      left: -5%;
    }

    .two {
      width: 50px;
      height: 50px;
      background-color: rgba(196, 241, 190, 1);
      border: 10px solid rgba(136, 136, 136, .5);
      top: 40%;
      left: -4.8%;
    }

    .three {
      width: 40px;
      height: 40px;
      background-color: rgb(0, 255, 231);
      border: 10px solid rgba(136, 136, 136, .5);
      top: -40%;
      left: -5%;
    }

    .four {
      width: 80px;
      height: 80px;
      background-color: rgb(233, 210, 244);
      border: 10px solid rgba(136, 136, 136, .5);
      top: -10%;
      left: 5%;
    }

    .item:active {
      opacity: .75;
    }

    .item:hover {
      cursor: pointer;
    }
  </style>
</head>

<body>

  <div id="outerContainer">
    <div id="container">
      <div class="item one">

      </div>
      <div class="item two">


    </div>
  </div>

  <script>
    var container = document.querySelector("#container");
    var activeItem = null;

    var active = false;

    container.addEventListener("touchstart", dragStart, false);
    container.addEventListener("touchend", dragEnd, false);
    container.addEventListener("touchmove", drag, false);

    container.addEventListener("mousedown", dragStart, false);
    container.addEventListener("mouseup", dragEnd, false);
    container.addEventListener("mousemove", drag, false);

    function dragStart(e) {

      if (e.target !== e.currentTarget) {
        active = true;

        // this is the item we are interacting with
        activeItem = e.target;

        if (activeItem !== null) {
          if (!activeItem.xOffset) {
            activeItem.xOffset = 0;
          }

          if (!activeItem.yOffset) {
            activeItem.yOffset = 0;
          }

          if (e.type === "touchstart") {
            activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
            activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
          } else {
            console.log("doing something!");
            activeItem.initialX = e.clientX - activeItem.xOffset;
            activeItem.initialY = e.clientY - activeItem.yOffset;
          }
        }
      }
    }

    function dragEnd(e) {
      if (activeItem !== null) {
        activeItem.initialX = activeItem.currentX;
        activeItem.initialY = activeItem.currentY;
      }

      active = false;
      activeItem = null;
    }

    function drag(e) {
      if (active) {
        if (e.type === "touchmove") {
          e.preventDefault();

          activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
          activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
        } else {
          activeItem.currentX = e.clientX - activeItem.initialX;
          activeItem.currentY = e.clientY - activeItem.initialY;
        }

        activeItem.xOffset = activeItem.currentX;
        activeItem.yOffset = activeItem.currentY;

        setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
      }
    }

    function setTranslate(xPos, yPos, el) {
      el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
    }

    var xvalitem2= document.getElementById("item.two.yPos");
    var yvalitem2= document.getElementById("item.two.xPos");  
  </script>
</body>


<button type="button" onclick="document.write(xvalitem2)">Try it</button>
<button type="button" onclick="document.write(yvalitem2)">Try it</button>


</html>

您在两个元素中都设置了 class 属性而不是 id 属性

<div class="item one">
<!-- should be -->
<div id="item one">

然后可以通过id查询

您可以使用document.querySelector获取物品,例如

document.querySelector('.item.one')
document.querySelector('.item.two')

您可以使用 getBoundingClientRect() 来获取两个元素的位置。
运行控制台中的以下脚本或将其放在按钮元素之后,然后单击按钮后,您可以在控制台上看到结果。

let buttons = document.getElementsByTagName('button');
['one', 'two'].forEach((v, i) => {
  buttons[i].onclick = null;
  buttons[i].addEventListener('click', e => {
    let element = document.querySelector(`.item.${v}`);
    let bounding = element.getBoundingClientRect();
    console.log(`item ${v} x`, bounding.x);
    console.log(`item ${v} y`, bounding.y);
  });
});

顺便说一下,document.write 加载文档后不是一个好主意,因为它会消除之前的所有内容。

另外,您可以通过dragEnd函数获取拖动结束时的位置,无需点击任何按钮

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
  <title>Drag Multiple Elements</title>
  <style>
    #container {
      width: 100%;
      height: 400px;
      background-image: url('http://www.unisg.bplaced.net/park.png');
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 7px;
      touch-action: none;
    }

    .item {
      border-radius: 50%;
      touch-action: none;
      user-select: none;
      position: relative;
    }

    .one {
      width: 50px;
      height: 50px;
      background-color: rgb(245, 230, 99);
      border: 10px solid rgba(136, 136, 136, .5);
      top: 40%;
      left: -5%;
    }

    .two {
      width: 50px;
      height: 50px;
      background-color: rgba(196, 241, 190, 1);
      border: 10px solid rgba(136, 136, 136, .5);
      top: 40%;
      left: -4.8%;
    }

    .three {
      width: 40px;
      height: 40px;
      background-color: rgb(0, 255, 231);
      border: 10px solid rgba(136, 136, 136, .5);
      top: -40%;
      left: -5%;
    }

    .four {
      width: 80px;
      height: 80px;
      background-color: rgb(233, 210, 244);
      border: 10px solid rgba(136, 136, 136, .5);
      top: -10%;
      left: 5%;
    }

    .item:active {
      opacity: .75;
    }

    .item:hover {
      cursor: pointer;
    }

    #position {
      position: absolute;
      top: 0;
    }
  </style>
</head>

<body>

  <div id="outerContainer">
    <div id="container">
      <div class="item one">

      </div>
      <div class="item two">

    </div>
  </div>
  <div id="position"></div>
  <script>
    var container = document.querySelector("#container");
    var activeItem = null;
    var oneX, oneY, twoX, twoY;
    ['one', 'two'].forEach((v, i) => {
      let element = document.querySelector(`.item.${v}`);
      let bounding = element.getBoundingClientRect();
      window[`${v}X`] = Math.round(bounding.x);
      window[`${v}Y`] = Math.round(bounding.y);
    });

    var active = false;

    container.addEventListener("touchstart", dragStart, false);
    container.addEventListener("touchend", dragEnd, false);
    container.addEventListener("touchmove", drag, false);

    container.addEventListener("mousedown", dragStart, false);
    container.addEventListener("mouseup", dragEnd, false);
    container.addEventListener("mousemove", drag, false);

    function dragStart(e) {

      if (e.target !== e.currentTarget) {
        active = true;

        // this is the item we are interacting with
        activeItem = e.target;

        if (activeItem !== null) {
          if (!activeItem.xOffset) {
            activeItem.xOffset = 0;
          }

          if (!activeItem.yOffset) {
            activeItem.yOffset = 0;
          }

          if (e.type === "touchstart") {
            activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
            activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
          } else {
            console.log("doing something!");
            activeItem.initialX = e.clientX - activeItem.xOffset;
            activeItem.initialY = e.clientY - activeItem.yOffset;
          }
        }
      }
    }

    function dragEnd(e) {
      if (activeItem !== null) {
        activeItem.initialX = activeItem.currentX;
        activeItem.initialY = activeItem.currentY;
        var bounding = activeItem.getBoundingClientRect();
        window[`${activeItem.classList[1]}X`] = Math.round(bounding.x);
        window[`${activeItem.classList[1]}Y`] = Math.round(bounding.y);
        let position = document.getElementById('position');
        position.innerHTML = `
          <p>oneX: ${oneX}</p>
          <p>oneY: ${oneY}</p>
          <p>twoX: ${twoX}</p>
          <p>twoX: ${twoY}</p>
        `
      }

      active = false;
      activeItem = null;
    }

    function drag(e) {
      if (active) {
        if (e.type === "touchmove") {
          e.preventDefault();

          activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
          activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
        } else {
          activeItem.currentX = e.clientX - activeItem.initialX;
          activeItem.currentY = e.clientY - activeItem.initialY;
        }

        activeItem.xOffset = activeItem.currentX;
        activeItem.yOffset = activeItem.currentY;

        setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
      }
    }

    function setTranslate(xPos, yPos, el) {
      el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
    }

    var xvalitem2= document.getElementById("item.two.yPos");
    var yvalitem2= document.getElementById("item.two.xPos");  
  </script>
</body>
</html>