Angularjs获得元素位置

use*_*781 12 javascript jquery angularjs

在jQuery中,我们可以使用以下方法获取对象的位置:

$(this).position().left;
Run Code Online (Sandbox Code Playgroud)

我们如何使用AngularJS获取当前元素位置?

A.B*_*A.B 36

你可以使用angular jqlite中的prop().选择一个元素你可以使用querySelector()返回第一个匹配元素或querySelectorAll()返回所有匹配元素

angular.element(document.querySelector('yourelement')).prop('offsetLeft');
Run Code Online (Sandbox Code Playgroud)

或者如果你的"this"是有效的dom元素

angular.element(this).prop('offsetLeft');
Run Code Online (Sandbox Code Playgroud)

div的例子

您可以在html中使用$ event引用DOM对象,并将其传递给控制器​​上的函数

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

在控制器中

$scope.myfunction = function($event){
 console.log(angular.element($event.target).prop('offsetLeft'));

}
Run Code Online (Sandbox Code Playgroud)

演示

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)

}
  
});
Run Code Online (Sandbox Code Playgroud)
.divvy{position:absolute; left:60px;
width:100px; background:red;
}
Run Code Online (Sandbox Code Playgroud)
   

<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>
Run Code Online (Sandbox Code Playgroud)