首页 > 解决方案 > 获取移动元素的当前位置 - 鼠标点击

问题描述

我有一个从 A 点移动到 B 点的 HTML 元素。

我想在元素移动到 B 点时单击鼠标来获取该元素的特定位置。

我怎样才能做到这一点?

HTML

<div id="contentContainer">
  <div id="thing"></div>
</div>

css

#thing {
border-radius: 50%;
position: absolute;
width: 40px;
height: 40px;
left: 0px;
top: 0px;
background-color: red;
transition: 1s cubic-bezier(.5, .51, .7, .68),
            1s cubic-bezier(.5, .51, .7, .68);

}

js

var theThing= document.querySelector("#thing");
var container = document.querySelector("#contentContainer");

//create random position to move the #thing to it 
var xPosition =  Math.random()*(container.clientWidth-40);
var yPosition = Math.random()*(container.clientHeight-40);

// add the new position  
theThing.style.left = xPosition + "px";
theThing.style.top = yPosition + "px";

container.addEventListener("click", function(event) {
//here i want to click to get current specific position of #thing
}

标签: javascript

解决方案


检查此代码:

// Code goes here
window.onload = function() {
  var theThing = document.querySelector("#thing");
  var container = document.querySelector("#contentContainer");

  //create random position to move the #thing to it 
  var xPosition = Math.random() * (container.clientWidth - 40);
  var yPosition = Math.random() * (container.clientHeight - 40);

  // add the new position  
  theThing.style.left = xPosition + "px";
  theThing.style.top = yPosition + "px";
  document.body.addEventListener("click", function(event) {
    var pos = getPosition(theThing);
    alert(pos.top + "," + pos.left);
  });
}

function getPosition(element) {
  var x = window.scrollX + element.getBoundingClientRect().left;
  var y = window.scrollY + element.getBoundingClientRect().top;
  return {
    top: x,
    left: y
  };
}

推荐阅读