angularJS - 从div中的mouseclick获取x和y位置

M. *_*nho 35 javascript position angularjs

我创建了一个函数,它应该在我在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,
        })
}
Run Code Online (Sandbox Code Playgroud)

Liv*_* T. 61

你需要改变event.x,以event.offsetXevent.yevent.offsetY

您没有添加模板定义,但我会添加它以防万一:

<div ng-click="addOnClick($event)"></div>
Run Code Online (Sandbox Code Playgroud)

  • 小心Firefox没有offsetX.[用途layerX用于Firefox](http://stackoverflow.com/questions/8878471/return-coordinates-of-mouse-click-on-html5-canvas-using-javascript-mouse-events) (18认同)

小智 5

在 html 文件中,使用:

<div (click)="test($event)"></div>
Run Code Online (Sandbox Code Playgroud)

并在ts文件中的函数中::

function test(e){
 console.log(e.clientX);
 console.log(e.clientY);
}
Run Code Online (Sandbox Code Playgroud)