JS pageX and pageY take the coordinate plus the margin of relative position div?

北慕城南 提交于 2019-12-11 10:49:36

问题


I have a div that I want to center so I use

margin-left: auto;
margin-right: auto;
position: relative;

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 :

http://jsfiddle.net/FGkUq/

Any ideas how to fix so to show the square to the coordinates without the left margin ?


回答1:


Take a look at the updated fiddle.

Quick solution remove positioning of canvas:

#canvasDiv { 
    width: 30%;
    height: 400px;  
    cursor:crosshair;  
    background-color: #458B00; 
    /* position: 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.

Therefore the position of #template will take into consideration the position of #canvasDiv unless you leave #canvasDiv with the default static positioning.

Learn more about positioning at w3schools

Positioning absolutely elements inside relatively positioned elements: here

Great example of your problem tabs 3 & 4.

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
};

Check out the fiddle



来源:https://stackoverflow.com/questions/16479179/js-pagex-and-pagey-take-the-coordinate-plus-the-margin-of-relative-position-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!