Javascript angularJS - 从 div 中的鼠标单击获取 x 和 y 位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14389986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angularJS - getting x & y positions from mouseclick in div
提问by M. Winterinho
I made a function that should add an item on the position I clicked inside a div. Now the problem with this function is, every time I click, it takes the x & y position of the document, not the x & y position inside the div. So what I actually want, is that the top-left corner of my div should give x=0 & y=0, but I don't know if this is possible? And I guess there is another way to do this..
我做了一个函数,应该在我在 div 内单击的位置上添加一个项目。现在这个函数的问题是,每次我点击时,它都会获取文档的 x & y 位置,而不是 div 内的 x & y 位置。所以我真正想要的是,我的 div 的左上角应该给 x=0 & y=0,但我不知道这是否可能?我想还有另一种方法可以做到这一点..
$scope.addOnClick = function(event) {
$scope.items.push( {
"label": "Click",
"value": 100,
"x": event.x-50,
"y": event.y-50,
})
}
回答by Liviu T.
You need to change event.xto event.offsetXand event.yto event.offsetY
你需要改变event.x,以event.offsetX和event.y对event.offsetY
You didn't add the template definition but I'll add it just in case:
您没有添加模板定义,但我会添加它以防万一:
<div ng-click="addOnClick($event)"></div>
回答by Dudu Madeira
In html file, use:
在 html 文件中,使用:
<div (click)="test($event)"></div>
And in the function in the ts file::
并在 ts 文件中的函数中:
function test(e){
console.log(e.clientX);
console.log(e.clientY);
}
回答by Dr Manhattan
For those on angular who are using dragging libraries and want the position of the element that was dragged:
对于那些正在使用拖动库并希望被拖动元素的位置的 angular:
<div ng-click="OnDrag($event)"></div>
and in the controller
并在控制器中
$scope.onDrag($event){
console.log("X ->",$event.originalEvent.pageX,"Y ->",$event.originalEvent.pageY)
}

