【问题标题】:CSS Zoom property not working with BoundingClientRectangleCSS Zoom 属性不适用于 BoundingClientRectangle
【发布时间】:2017-10-31 19:48:46
【问题描述】:

使用“缩放”属性转换元素后,我无法获取元素的坐标。我需要知道所有 4 个角的坐标。我通常会使用 getBoundingClientRect 属性来完成此操作,但是在缩放元素时似乎无法正常工作。我附上了一个简短的 jsfiddle 链接来显示什么似乎不起作用。我使用的是 Chrome,但 Firefox 也存在这种行为。

http://jsfiddle.net/GCam11489/0hu7kvqt/

HTML:

<div id="box" style="zoom:100%">Hello</div><div></div><div></div>

JS:

var div = document.getElementsByTagName("div");
div[1].innerHTML = "PreZoom Width: " + div[0].getBoundingClientRect().width;
div[0].style.zoom = "150%";
div[2].innerHTML = "PostZoom Width: " + div[0].getBoundingClientRect().width;

当我运行该代码时,前后缩放宽度均显示“100”。

我找到了很多信息,但我发现的所有信息似乎都表明这是 Chrome 上的一个已知错误,并且已经修复。有谁知道如何纠正这种情况或我可能做错了什么?

【问题讨论】:

    标签: javascript css transform


    【解决方案1】:

    This comment 在错误报告中详细介绍了 reg。这个问题,但它的状态似乎是“WontFix”,所以你可能在那里不走运。

    一些替代方案:

    • 如果您使用transform: scale(1.5) 而不是缩放,您会在getBoundingClientRect() 中获得正确的值,但它会与页面布局混淆。
    • 您可以使用window.getComputedStyle(div[0]).zoom 获取元素的缩放值(以十进制表示)并将其乘以getBoundingClientRect() 的宽度

    【讨论】:

    • 你不能依赖window.getComputedStyle(div[0]).zoom,因为父DomNode上的zoom样式不会反映在当前节点上。
    【解决方案2】:

    这是一篇相当老的帖子,但我遇到了同样的问题,我在一个小面板上有一个角材质项目,它的像素比低于 1,这使得一切都非常小。为了解决这个问题,我在身体上添加了一个缩放来解决这个问题。

    角度材料 (7) 滑块使用getBoundingClientRect() 来确定它的位置,这使滑块走得比我希望的更远。

    我使用了像上面提到的博学精神这样的解决方案。

    if (Element.prototype.getBoundingClientRect) {
      const DefaultGetBoundingClientRect = Element.prototype.getBoundingClientRect;
      
      Element.prototype.getBoundingClientRect = function () {
        let zoom = +window.getComputedStyle(document.body).zoom;
        let data = DefaultGetBoundingClientRect.apply(this, arguments);
    
        if (zoom !== 1) {
          data.x = data.x * zoom;
          data.y = data.y * zoom;
          data.top = data.top * zoom;
          data.left = data.left * zoom;
          data.right = data.right * zoom;
          data.bottom = data.bottom * zoom;
          data.width = data.width * zoom;
          data.height = data.height * zoom;
        }
    
        return data;
      };
    }

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 2021-10-23
      • 2021-08-07
      • 2020-10-06
      • 2017-10-31
      • 2016-07-16
      • 1970-01-01
      • 2014-10-14
      相关资源
      最近更新 更多