JS pageX和pageY取坐标加上相对位置div的边距? [英] JS pageX and pageY take the coordinate plus the margin of relative position div?
问题描述
我有一个div,我想使用
I have a div that I want to center so I use
margin-left: auto;
margin-right: auto;
position: relative;
这是最容易让我承认的方法,但是当我想使用event.pageX和event。 pageY它需要坐标加上左边距,这是错误的。
That's the easiest way to center I admit, but when I want to use event.pageX and event.pageY it takes the coordinates plus the left margin and that's wrong.
这里是小提琴。点击绿色矩形上的某处可查看结果:
Here is the fiddle. Click somewhere on the green rectangle to watch the result :
任何想法如何解决这个问题,以显示正方形到没有左边距的坐标?
Any ideas how to fix so to show the square to the coordinates without the left margin ?
推荐答案
查看更新小提琴。
快速解决方法删除画布的定位:
Quick solution remove positioning of canvas:
#canvasDiv {
width: 30%;
height: 400px;
cursor:crosshair;
background-color: #458B00;
/* position: relative; */
...
}
问题是模板。因为 absolute
仍然是relative。
The problem is with the positioning of template. Because absolute
is still "relative".
绝对定位的定义:
The definition of absolute positioning: An absolute position element is positioned relative to the first parent element that has a position other than static.
因此, #template $ c的位置相对于第一个父元素$ c>将考虑
#canvasDiv
的位置,除非您将 #canvasDiv
与默认值 static
定位。
Therefore the position of #template
will take into consideration the position of #canvasDiv
unless you leave #canvasDiv
with the default static
positioning.
有关定位的详情,请访问 w3schools
Learn more about positioning at w3schools
在相对定位的元素中定位绝对元素:这里
Positioning absolutely elements inside relatively positioned elements: here
伟大的您的问题示例标签3& 4。
Great example of your problem tabs 3 & 4.
如果你想坚持 canvasDiv
的相对定位,你必须更新脚本,它考虑 canvasDiv
的位置:
Should you wish to stick with the relative positioning of canvasDiv
, you have to update the script, so it takes into account the positioning of canvasDiv
:
var x = event.pageX;
var y = event.pageY;
var canvasPos = $(this).offset(); // in the context of your script this refers to #canvasDiv
var styles = {
"left" : x - canvasPos.left, // remove its left offset
"top" : y - canvasPos.top // remove its top offset
};
查看 fiddle
这篇关于JS pageX和pageY取坐标加上相对位置div的边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!