getBoundingClientRect在IE9/10里的bug

getBoundingClientRect可以获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,最早在IE中实现,后其它浏览器均已实现。

 

但它在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

 

点击试试看,可以看到在IE9/10下一直为0

 

 

 

相关:

http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx

http://developer.mozilla.org/en/docs/DOM:element.getBoundingClientRect

http://ejohn.org/blog/getboundingclientrect-is-awesome/

 

posted on 2013-12-20 11:16  snandy  阅读(2721)  评论(1编辑  收藏  举报