javascript - 获取移动元素的当前位置 - 鼠标点击
问题描述
我有一个从 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
}
解决方案
检查此代码:
// 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
};
}
推荐阅读
- ruby-on-rails - Rails 端点性能 - 寻找什么?
- python - 非常具体的应用程序的递归算法(Python)
- spring - JPA/Spring/Hibernate/etc 中是否有类似于 JPA 的 @PrePersist 允许更改相关实体的功能?
- google-apps-script - 谷歌课堂表格
- swagger - Swagger - 属性名称约定
- python - 如何键入检查引用类的数据类函数?
- sql-server - SQL 配置中没有 sqlbrowser
- azure - 使用 Docker 构建的 Azure DevOps 变得越来越慢
- java - 如何使用数字或字母验证在 jtextfield 中键入下划线
- laravel - 在 Laravel 中,如何在 Route::middleware 组中使用“cannot”?