javascript - 在子元素的指令中获取 CSS 属性

标签 javascript css angularjs dom

我目前正在循环遍历指令附加到的元素的子元素,并为 mouseup 和 mousedown 添加回调:

    var dragDroppables = element[0].children;

    for (var elementIdx = 0; elementIdx < dragDroppables.length; elementIdx++) {
        var bindElement = dragDroppables[elementIdx];

        var elementID = bindElement.attributes['id'].value;

        if(elementID == "DragDroppable") {

            var bindElementAngular = angular.element(bindElement);

            bindElementAngular.on('mousedown', function() {
                bindElementAngular.css('background-color', 'rgb(17, 83, 252)');            
                elementHeldDown = bindElementAngular;
                isElementHeldDown = true;

                //window and angular.window are both undefined in this case
                var style = angular.window.getComputedStyle(bindElementAngular);         
                heldDownElementWidth = parseInt(style.getPropertyValue('width'));
                heldDownElementHeight = parseInt(style.getPropertyValue('height'));     
            });
            bindElementAngular.on('mouseup', function () {
                bindElementAngular.css('background-color', 'rgb(73, 122, 255)');
                isElementHeldDown = false;
            });
          }
       }
    }

现在它提示窗口对象未定义。当我在 Controller 中具有此功能时,直接获取窗口对象(无需从 Angular 对象调用它)工作正常。现在它在指令中似乎不再起作用了。如何从指令内的任意 DOM 对象获取 CSS 属性?

最佳答案

尝试在指令中注入(inject)window对象

directives.insertStyle = [ "$window", function($window){
    return {
        link: function(scope, element, attrs) {
            var elementStyleMap = $window.getComputedStyle(element[0], null);

        }
    }   
}];

关于javascript - 在子元素的指令中获取 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47400139/

相关文章:

javascript - 如何在访问者退出网站时弹出

javascript - 根据是否选择文件更改文件上传边框的颜色

html - 在表格单元格中包装单词,但固定表格布局使列大小相等

javascript - 在 JSON 源数据中使用 AngularJS 表达式

angularjs - 使用 Angularjs 加密客户端本地存储数据

javascript - 使用自定义过滤器时 ng-bind 失败

javascript - 如何使用 XMLHttpRequest 设置 Access-Control-Allow-Origin header

javascript - ReactJS 通过 map 迭代渲染多个 UI 组件

javascript - 如何正确转义和取消转义包含换行文字的多行字符串?

css - 带有 svg 和 css 的动画背景