使用指令刷新窗口时刷新元素的高度和大小 [英] Refresh element height and size on window refresh with directive
本文介绍了使用指令刷新窗口时刷新元素的高度和大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,以下指令在页面加载时获取元素的宽度和高度.如何在窗口调整大小时刷新它?
At the moment, the following directive grabs the width and height of an element on page load. How do I get it to refresh it on window resize?
angular.module('adsomaApp')
.directive('elementSize', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.ready(function () {
var height, width;
$timeout(function () {
height = element[0].offsetHeight;
width = element[0].offsetWidth;
if (attrs.key) {
scope[attrs.key] = {
height: height,
width: width
};
return;
}
scope.elementSize = {
height: height,
width: width
};
});
});
}
};
});
推荐答案
目前尚不清楚该指令的目的是什么(即elementSize
过去是什么,目的是什么),但为什么不直接使用$window
resize
?这里是重构版本:
It is not clear what the purpose of the directive is (i.e what is elementSize
used to, what is the purpose) but why not just hook into $window
resize
? Here a refactored version :
.directive('elementSize', function($timeout, $window) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var height, width;
var measure = function() {
height = element[0].offsetHeight;
width = element[0].offsetWidth;
if (attrs.key) {
scope[attrs.key] = {
height: height,
width: width
};
}
scope.elementSize = {
height: height,
width: width
};
//log values
console.log(scope.elementSize)
}
$timeout(function() {
measure()
});
angular.element($window).bind('resize', function() {
measure()
})
}
};
});
当我调整窗格大小时似乎可以工作-> http://plnkr. co/edit/qOAQeWUYBcgeWgvEcBKk?p = preview
Seems to work when I resize the panes -> http://plnkr.co/edit/qOAQeWUYBcgeWgvEcBKk?p=preview
但是,再次不确定,这是否真的是您的想法.
But again, not sure if this really is what you have in mind.
这篇关于使用指令刷新窗口时刷新元素的高度和大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文