[英]How to get the cursor position within a centered div?
I was making a drawing app and I had to center it. 我当时正在制作绘图应用程序,因此必须居中。
To detect the cursor position I used 为了检测我使用的光标位置
$('#drawbox').mousedown(function(e){
paint = true;
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
addClick(e.pageX-this.offsetLeft, e.pageY-this.offsetTop);
redraw();
});
the drawbox div is wrapped in a centering div with the following style 绘制框div被包装在具有以下样式的居中div中
position:relative;
margin:auto;
text=align:center;
It resulted in my drawings being out of bounds, for some reasons it was working fine without the centering wrapper div. 这导致我的绘图超出范围,由于某些原因,在没有居中包装div的情况下它可以正常工作。 thanks you for your help
谢谢你的帮助
Here is a fiddle for demo 这是演示的小提琴
https://jsfiddle.net/ok0ohbxj/ https://jsfiddle.net/ok0ohbxj/
Refering to the fiddle you posted in a comment to your question, the problem is your usage of offsetTop
: 参考您在问题评论中发布的小提琴,问题在于您使用
offsetTop
:
The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.
HTMLElement.offsetTop只读属性返回当前元素相对于offsetParent节点顶部的距离。
In your case, the offsetParent node is the wrapping container .centerHelper
not your document. 在您的情况下,offsetParent节点是包装容器
.centerHelper
而不是您的文档。
Since you're already using jQuery, i suggest to go with $('drawbox').offset()
instead, which returns the offset relative to the document: 由于您已经在使用jQuery,所以我建议
$('drawbox').offset()
,它返回相对于文档的偏移量:
$('#drawbox').mousedown(function(e){
paint = true;
var mouseX = e.pageX - $('#drawbox').offset().left;
var mouseY = e.pageY - $('#drawbox').offset().top;
addClick(mouseX, mouseY);
redraw();
});
$('#drawbox').mousemove(function(e){
if (paint){
var mouseX = e.pageX - $('#drawbox').offset().left;
var mouseY = e.pageY - $('#drawbox').offset().top;
addClick(mouseX,mouseY, true);
redraw();
}
});
And a fiddle for you to try out: https://jsfiddle.net/6gwnexjL/ 还有一个小提琴供您试用: https : //jsfiddle.net/6gwnexjL/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.