我有一个从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
}
答案 0 :(得分:0)
检查此代码:
// 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
};
}