【问题标题】:Angular directive works with inline style but not with classAngular 指令适用于内联样式,但不适用于类
【发布时间】:2015-04-14 23:46:53
【问题描述】:

我有这个指令:

angular.module('exampleApp').directive('exampleDirective', ['$document', '$window', function($document, $window) {
    return {
        restrict: 'E',
        scope: false,
        template: '<div class="foo"></div>',
        link: function($scope, $element, $attrs) {
            var targetElement = angular.element(document.querySelector($attrs['targetSelector']));
            console.log(targetElement.css('height'));
        }
   }
]);

这个 html 效果很好:

 <div id="div1" style="height: 100px">A div</div>
 <example-directive target-selector="#div1" />

因为在控制台中我看到:“100px”打印出来了

但是有了这个 html:

 <style>
      .div-example {
          height: 100px;
      }
 </style>

 <div id="div2" class="div-example">A div</div>
 <example-directive target-selector="#div2" />

基本相同,但没有内联样式,该指令根本不起作用。控制台正在打印:“”(空字符串)。

我该如何解决这个问题?
我试过scope: true,但也没有用。
targetElement.css('height') 是否只适用于内联样式?

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

当您执行.css('height') 时,jQuery 只能告诉您在元素的style 属性或属性中设置的值。

如果您想知道元素的实际高度,请尝试使用

targetElement[0].clientHeight

或者使用 jQuery:

targetElement.height()

这里的区别解释得更好一点:https://api.jquery.com/height/

【讨论】:

  • 但我什至没有使用 jquery...这是 angular 自己的 jqLit​​e(我认为这就是它的名称)
  • targetElement.clientHeight 也给我 undefined
  • 对不起,应该更好地指定它。您的 targetElement 是一个 jqlite 对象,而 clientHeight 是实际 DOM 元素的属性。使用.height() 或使用.get(0).clientHeight
  • 标记为已接受,尽管我最终使用了这个:window.getComputedStyle(targetElement[0], null).getPropertyValue("height"),因为我需要计算出的高度,而不是 clientHeightoffsetHeight
猜你喜欢
  • 2018-09-26
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多