在angularJS中,我们可以使用指令来访问元素,也可以使用这些指令设置属性。我希望在不使用指令的情况下获得/设置DOM元素的一些属性。
<div class=main ng-app="myApp" ng-controller="SalesController">
<div class=ele1> </div>
<div class=ele2> </div>
<div class=ele3></div>
</div>在某些地方,我希望某些元素的高度能做一些计算:
var myApp = angular.module('myApp', []);
myApp.controller('SalesController',function($scope){
//this code not working
document.getElementsByClassName("ele1").clientHeight;
}); 我知道如何使用指令获得高度,但在某些情况下,我们需要项目不同部分的div元素的高度/宽度,每次添加指令都会增加代码。
在angularjs (如jquery中的$("classname").height() )中,是否有单行方法来查找div的高度/宽度?我宁愿不使用jQuery就这样做。
发布于 2016-10-24 10:22:51
我们可以使用javascript或角js访问元素,在上面的回答中,他们使用javascript访问elements.In角js,我们可以在控制器中注入$element,我们可以使用类或id访问任何元素。
myApp.controller('SalesController',function($scope,$element){
//here we are using 2 indexes but that is not the position index of child elements
var temp=$element[0].getElementsByClassName('ele1')[0].clientHeight;
}); 发布于 2016-10-20 14:26:43
您可以使用height/width循环找到DOM元素的JavaScript。
示例:
var myApp = angular.module('myApp', []);
myApp.controller('SalesController',function($scope){
var objects = document.getElementsByClassName('YOUR_CLASS_NAME');
var height = 0;
for(var i=0;i<objects.length;i++){
height = objects[i].clientHeight;
console.log(height); /*Output in JS console*/
alert(height); /*Output in window alert Box*/
}
});注释: document.getElementsByClassName()函数返回对象数组。
document.getElementById()返回单个对象。不能在对象数组选择器中直接使用clientHeight属性。因为clientHeight是单个对象属性。
其他一些JavaScript DOM选择器函数
document.getElementById() /*Return single Object*/
document.getElementsByTagName() /*Return Object Array*/
document.getElementsByTagNameNS()
document.getElementsByName()
document.querySelector()
document.querySelectorAll()
....https://stackoverflow.com/questions/40156695
复制相似问题