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

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

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

This is the easiest way to focus, I admit, but when I want to use event.pageX and event.pageY, it takes the coordinates plus the left margin and this is wrong.

Here is the fiddle. Click somewhere on the green rectangle to see the result:

http://jsfiddle.net/FGkUq/

Any ideas how to fix it to show a square to coordinates without a left margin?

+1
source share
1 answer

Take a look at the updated script .

A quick fix removes the positioning of the canvas:

 #canvasDiv { width: 30%; height: 400px; cursor:crosshair; background-color: #458B00; /* position: relative; */ ... } 

The problem is the positioning of the template. Since absolute is still "relative".

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 #template position will consider the position of #canvasDiv unless you leave #canvasDiv with the default static position.

More on positioning on w3schools

Positioning absolutely elements inside relatively positioned elements: here

A great example of your problem is tabs 3 and 4.

If you want to adhere to the relative positioning of the canvasDiv , you need to update the script, so it takes into account the location of the 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 }; 

Look fiddle

+1
source

Source: https://habr.com/ru/post/1204486/


All Articles