CSS 在 AngularJS 中获取没有 JQuery 的 HTML 元素高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21895732/
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
Get HTML Element Height without JQuery in AngularJS
提问by user3284007
I'm getting familiar with AngularJS. I'm trying to be as 'pure' as I can. For that reason, I'm trying to avoid including jQuery. However, I'm having a challenge getting an HTML element's height. Currently, I'm trying the following:
我开始熟悉 AngularJS。我尽量做到“纯洁”。出于这个原因,我试图避免包含 jQuery。但是,我在获取 HTML 元素的高度时遇到了挑战。目前,我正在尝试以下操作:
angular.module('myModule', [])
.directive('myDirective', function() {
return {
restrict: 'A',
link: function(scope, element) {
console.log(element.css('height'));
}
};
})
;
However, when this code gets executed, an empty line gets written to the console. I'm trying to display the height of the element. Is there a way to do this in AngularJS without using jQuery?
然而,当这段代码被执行时,一个空行被写入控制台。我正在尝试显示元素的高度。有没有办法在不使用 jQuery 的情况下在 AngularJS 中做到这一点?
Thank you!
谢谢!
回答by shaunhusain
It appears this is working correctly and gives the same result if you use:
如果您使用以下命令,它似乎可以正常工作并给出相同的结果:
element.style.height
Since no inline style or CSS height is set on the element a blank line is shown. Instead of relying on the style you can get the HTML elements height directly.
由于没有在元素上设置内联样式或 CSS 高度,因此显示了一个空行。您可以直接获取 HTML 元素的高度,而不是依赖样式。
console.log(element[0].offsetHeight);
http://plnkr.co/edit/03YWwjBjYpid4fVmDxlM?p=preview
http://plnkr.co/edit/03YWwjBjYpid4fVmDxlM?p=preview
How do I retrieve an HTML element's actual width and height?
回答by IxDay
The small wrapper around element provided by angular allows you to ask for properties, so:
angular 提供的元素周围的小包装器允许您请求属性,因此:
element.prop('offsetHeight');
Will just work fine, see: http://plnkr.co/edit/pFHySDo7hjEcMKCqGuiV?p=preview
会正常工作,请参阅:http: //plnkr.co/edit/pFHySDo7hjEcMKCqGuiV?p=preview