[英]getBoundingClientRect() returning wrong width
I'm using Angular Material
for my grid system. 我正在为我的网格系统使用
Angular Material
。 I'm trying to generate an SVG and it is supposed to show me the width of the element, however it is getBoundingClientRect()
is returning 300px
despite the width being 618px
. 我正在尝试生成一个SVG,它应该向我显示元素的宽度,但是尽管宽度为
618px
,但是getBoundingClientRect()
返回300px
。 I tried it again making my window smaller but it still showed up as 300px
even though this time it was actually 100px
.. 我再次尝试使我的窗口变小但它仍然显示为
300px
即使这次它实际上是100px
..
This is my HTML: 这是我的HTML:
<div layout="row" layout-wrap layout-padding>
<div flex="33" ng-repeat="result in ctrl.results">
<svg height="100%" width="100%" position>
<rect x="0" y="0" width="100%" height="100%" fill="#da552f"></rect>
<text fill="#ffffff" x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-size="48" font-family="Verdana">Hello World</text>
</svg>
</div>
</div>
and this is my angularjs directive for the position
attribute: 这是我对
position
属性的angularjs指令:
var app = angular.module('MainDirective', []);
app.directive('position', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
var rect = element[0].getBoundingClientRect();
var text = element.children()[1].getBBox();
console.log(rect)
}
};
});
There is no custom CSS in my project. 我的项目中没有自定义CSS。
Any thoughts why this might be happening? 有什么想法可能会发生这种情况吗? I've tried so many different variations of
getBoundingClientRect()
but they all returned 300
... 我尝试了很多不同的
getBoundingClientRect()
变种,但它们都返回了300
...
Edit: just as proof: 编辑:就像证明:
I figured out what my issue was.. I should've used angulars $scope.$watch
as I was generating the svg
on an event click. 我想出了我的问题是什么..我应该使用angulars
$scope.$watch
因为我在点击事件时生成了svg
。
var app = angular.module('MainDirective', []);
app.directive('position', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
var rect, image, text;
$scope.$watch(element, function () {
rect = element[0].clientWidth;
image = element.children()[1].getBBox();
text = element.children()[2].getBBox();
console.log("Rect: "+rect+" image: "+image.width+" text: "+text.width)
});
}
};
});
Width calculation for elements that are not explicitly sized can get pretty weird: 300px is the reported width when the browser "gives up". 未明确调整大小的元素的宽度计算可能会非常奇怪:300px是浏览器“放弃”时报告的宽度。 I'm paraphrasing, but the detailed description is here:
我在解读,但详细说明如下:
https://www.w3.org/TR/CSS2/visudet.html#Computing_widths_and_margins https://www.w3.org/TR/CSS2/visudet.html#Computing_widths_and_margins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.