使用getBoundingClientRect()计算边界框

Calculating bounding box using getBoundingClientRect() Issue with swift top, left

本文关键字:边界 计算 getBoundingClientRect 使用      更新时间:2023-09-26

我有一个绝对位置的div target,我需要创建另一个div bb,它完全匹配/重叠 target的边界框。

下面的脚本工作,但在相同的旋转,如80度,div bb的位置不保持

我想知道:

  • 我的代码做错了什么?如何解决这个问题?
  • 或者可能是一个问题getBoundingClientRect()?

注意:div bb匹配div target的初始位置,我需要只使用CSS translate快速bb

http://jsbin.com/josufehano/1/(铬)

Issue可能在以下函数中,但任何其他反馈都是非常感谢的。谢谢。

    calculate: function () {
        var elm = document.getElementById(this.config.target.id);
        var rect = elm.getBoundingClientRect();
        this.data.br.width = rect.width;
        this.data.br.height = rect.height;
        // calculate swift
        this.data.br.left = -Math.abs(this.data.br.width - this.data.width) / 2;
        this.data.br.top = -Math.abs(this.data.br.height - this.data.height) / 2;
    },

我已经用下面的脚本解决了我的问题。基本上我需要它考虑旋转时,计算上/左swift。

http://jsbin.com/hejemixolu/1/

        calculate: function () {
            var elm = document.getElementById(this.config.target.id);
            var rect = elm.getBoundingClientRect();
            this.data.br.width = rect.width;
            this.data.br.height = rect.height;
            this.data.br.left = rect.left;
            this.data.br.top = rect.top;
            if (this.data.br.left <= this.data.left) {
                this.data.br.left = -Math.abs(this.data.left - this.data.br.left);
            } else {
                this.data.br.left = Math.abs(this.data.br.left - this.data.left);
            }
            if (this.data.br.top <= this.data.top) {
                this.data.br.top = -Math.abs(this.data.top - this.data.br.top);
            } else {
                this.data.br.top = Math.abs(this.data.br.top - this.data.top);
            }
        },