Javascript Angularjs 获取元素位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27581260/
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 get element position
提问by user1995781
In jQuery we can get position of an object with this:
在 jQuery 中,我们可以通过以下方式获取对象的位置:
$(this).position().left;
How can we get the current element position with AngularJS?
我们如何使用 AngularJS 获取当前元素位置?
回答by A.B
You can use prop() from angular jqlite. to select an element you can use querySelector() that returns first matching element or querySelectorAll() that return all matching element
您可以使用 angular jqlite 中的 prop()。要选择一个元素,您可以使用返回第一个匹配元素的 querySelector() 或返回所有匹配元素的 querySelectorAll()
angular.element(document.querySelector('yourelement')).prop('offsetLeft');
or if your "this" is valid dom element
或者如果您的“this”是有效的 dom 元素
angular.element(this).prop('offsetLeft');
Example for div
div 示例
you can reference the DOM object with $event in html and pass it to the function on controller
您可以在 html 中使用 $event 引用 DOM 对象并将其传递给控制器上的函数
<div ng-click="myfunction($event)"></div>
in controller
在控制器中
$scope.myfunction = function($event){
console.log(angular.element($event.target).prop('offsetLeft'));
}
Demo
演示
app = angular.module('test',[]);
app.controller('testctrl',function($scope){
$scope.myfunction = function($event){
console.log($event);
off =angular.element($event.target).prop('offsetLeft');
angular.element($event.target).text(off)
}
});
.divvy{position:absolute; left:60px;
width:100px; background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="testctrl" ng-app="test">
<div class="divvy" ng-click="myfunction($event)" >Click to see position</div>
</div>

