javascript 在 AnguarJS 中获取指令内的元素父高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31839031/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:26:09  来源:igfitidea点击:

Get element parent height inside directive in AnguarJS

javascriptangularjs

提问by Raymond the Developer

How do you get and set the parent height from an element from inside a directive?

如何从指令内部的元素获取和设置父高度?

This is what I have now, obviously it's not working.

这就是我现在所拥有的,显然它不起作用。

var vAlign = angular.module("vAlign", [])
.directive('vAlign', function() {
  return {
        restrict : "AC",
        link: function(scope, e){

            e.parent.height(1200);
            console.log(e.parent.height);
        }
    };
});

回答by dfsq

You can use parentand heightmethods of jqLite/jQuery:

您可以使用parentheightjqLit​​e / jQuery的方法:

link: function(scope, e) {
    e.parent().height(1200);
    console.log(e.parent().height());
}

Or you could do it in pure javascript with parentNodeproperty, which is a reference to parent element:

或者你可以在带有parentNode属性的纯 javascript 中完成,它是对父元素的引用:

link: function(scope, e) {
    e[0].parentNode.style.height = 1200 + 'px';
}

Also note, that since eis an jqLite/jQuery instance here which is a array-like collection of one single element, you need to use [0]to access raw HTMLElement.

另请注意,由于这里e是一个 jqLit​​e/jQuery 实例,它是一个类似数组的单个元素的集合,因此您需要使用[0]来访问原始 HTMLElement。

回答by Andy Newman

e.parent is a function, so you must call it as such:

e.parent 是一个函数,所以你必须这样调用它:

e.parent().height(1200);

Further, if you do not load jquery on the page, you will have to use

此外,如果您不在页面上加载 jquery,则必须使用

.css('height', '1200px')

instead, as jqLite does not include .height

相反,因为 jqLit​​e 不包括 .height