2

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 ?

4

1 回答 1

1

看看更新的小提琴

快速解决方案删除画布的定位:

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

问题在于模板的定位。因为absolute还是“相对”的。

绝对定位的定义:绝对位置元素相对于第一个具有非静态位置的父元素进行定位。

因此,除非您使用默认定位离开,否则 的位置#template将考虑 的位置。#canvasDiv#canvasDivstatic

了解有关在w3schools定位的更多信息

在相对定位的元素中定位绝对元素:这里

您的问题标签 3 和 4的绝佳示例。

如果您希望坚持使用 的相对定位canvasDiv,则必须更新脚本,因此它会考虑 的定位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
};

看看小提琴

于 2013-05-10T09:34:49.160 回答