---
title: "getBoundingClientRect在IE9/10里的bug"
author: "zhouyrt"
date: "2015-01-12T08:30:07Z"
tags: []
categories: ["Web前端"]
slug: "getboundingclientrect-ie9-10-bug"
draft: false
lastmod: "2015-01-12T08:30:07Z"
id: 2174905
url: "https://snandy.iteye.com/blog/2174905"
---

getBoundingClientRect可以获得页面中某个元素的左，上，右和下分别相对浏览器视窗的位置，最早在[IE](http://msdn.microsoft.com/en-us/library/ms536433%28VS.85%29.aspx)中实现，后其它浏览器均已实现。

 

但它在IE9,10中有个bug，当出现垂直滚动条时，获取top总为0。其它浏览器则能正常获取。代码如下

```
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>IE9/10 getBoundingClientRect bug</title>
    </head>
    <body style="height:3000px">
        <p style="margin-top:400px">
        <label>Top：<input id="_bound" type="text"/></label>
        </p>
        <script>
            var el = document.getElementById('_bound')
            document.onclick = function() {
                var rect = document.documentElement.getBoundingClientRect()
                el.value = rect.top           
            }
        </script>
    </body>
</html>
```

 

1\. 把body设的较高，以出现垂直滚动条

2\. 鼠标向下拖动滚动条大概200px

3\. 点击页面任意处，通过getBoundingClientRect获取input元素的top

 

Firefox/Chrome/Safari/IE11：-212~278

IE9/10：0

 

 

相关：

[http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx](http://msdn.microsoft.com/en-us/library/ms536433%28VS.85%29.aspx)

[http://developer.mozilla.org/en/docs/DOM:element.getBoundingClientRect](http://developer.mozilla.org/en/docs/DOM:element.getBoundingClientRect)

[http://ejohn.org/blog/getboundingclientrect-is-awesome/](http://ejohn.org/blog/getboundingclientrect-is-awesome/)