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

问题描述 投票:0回答:2

我正在尝试用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>
javascript getelementbyid document.write
2个回答
0
投票

您可以使用document.querySelector来获取项目,例如

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

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

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>

0
投票

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

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

然后您可以通过ID查询它

© www.soinside.com 2019 - 2024. All rights reserved.