getBoundingClientRect在Chrome中返回相同的值

getBoundingClientRect returning same value in Chrome

本文关键字:返回 Chrome getBoundingClientRect      更新时间:2023-09-26

我在Google Chrome中使用getBoundingClientRect()时遇到问题。我的代码如下:

React.js渲染:

render() {
    return (
        <div className="TapTwo-container" ref="clickContainer" onClick={this._handleTap}>
            <div id="TapTwo-forkContainer" className="TapTwo-forkContainer u-animationLinear u-animationLoop tapTwo-moveForkLeft" ref="fork">
                <img src="img/fork.png" className="tapTwo-fork"/>
            </div>
            <div className="TapTwo-pieContainer">
                <img src="img/pie.png" className="tapTwo-pie" />
                <img src="img/plate.png" className="tapTwo-plate"/>
            </div>
       </div>
    )
}

函数handleTap执行以下操作:

_handleTap() {
    let element = document.getElementById('TapTwo-forkContainer');
    let box = element.getBoundingClientRect()
    let top  = box.top;
    let left = box.left;
    console.log(Math.round(top),Math.round(left));
}

这里需要注意的是:TapTwo-forkContainer使用CSS进行动画+转换。它从屏幕的左侧移动到右侧,例如,其中一个关键帧:

@-webkit-keyframes moveForkLeft {
    0% {
         transform: translate(0,0);
    }
    100% {
        transform: translate(1250px, 0);
    }
}

当我在Firefox中测试它时,每次点击都会根据TapTwo-forkContainer的位置获得不同的值。然而,当我在谷歌浏览器(41.0.2272.118)中查看它时,我一次又一次地得到相同的值。

这里有一个演示(尝试垃圾邮件点击我按钮,并查看控制台中返回的值)

http://jsfiddle.net/d26cpdfk/4/

看起来getBoundingClientRect在Chrome中有缺陷。您可以使用getComputedStyle获取动画中的x或y值:

http://jsfiddle.net/d26cpdfk/1/

var element = document.getElementById('element')
    element.addEventListener('click', function(){
        console.log(element.getBoundingClientRect().left)
        var cs = window.getComputedStyle(element).transform
        var x = parseFloat(cs.split(', ')[4])
        console.log('getBoundingClientRect:',element.getBoundingClientRect().left, 'getComputedStyle:',x)
    }, false)