gpt4 book ai didi

javascript - 在 AngularJS 中不使用指令获取元素属性(高度/宽度)

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:01 26 4
gpt4 key购买 nike

在 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 中查找 div 的高度/宽度(如 jquery 中的 $("classname").height())?我宁愿在不使用 jQuery 的情况下这样做。

最佳答案

您可以使用 JavaScript 循环查找 DOM 元素的高度/宽度

示例:

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()
....

关于javascript - 在 AngularJS 中不使用指令获取元素属性(高度/宽度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40156695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com