javascript - getBoundingClientRect 在 Chrome 中返回相同的值

标签 javascript google-chrome reactjs

我在 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 的位置获得不同的值。但是,当我在 Google Chrome (41.0.2272.118) 中检查它时,我一遍又一遍地得到相同的值。

这是一个演示(尝试向“Click me”按钮发送垃圾邮件并查看控制台中返回的值)

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)

关于javascript - getBoundingClientRect 在 Chrome 中返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500716/

相关文章:

javascript - PHP call_user_func 像 Javascript 调用一样绑定(bind) thisArg

javascript - 从 url 获取 css id

javascript - Google Chrome 对我的 JS 代码没有响应?

css - Mix-blend-mode:乘法在 Chrome 中不起作用

javascript - 读取 list : Error processing content_script: An unexpected property was found in the WebExtension manifest

javascript - 如何在 Sequelize.js 中定义对象数组?

html - 根据内容调整 div 容器大小的官方属性或值是什么?

javascript - 渲染许多元素时 react 很慢

reactjs - 在 makeStyle() 中处理多个类名 - ReactJS

javascript - 是否使用 React-router?