---
title: "visual rect computation of element"
author: "yiminghe"
date: "2011-07-14T21:50:11Z"
tags: ["CSS", "HTML", "JavaScript", "UI", "Web"]
categories: ["Web前端"]
slug: "visual-rect-computation-of-element"
draft: false
lastmod: "2011-07-14T21:52:04Z"
id: 1124720
url: "https://yiminghe.iteye.com/blog/1124720"
---

# 元素的可视矩阵（区域）计算

 

  元素常常需要展现在用户的可视区域内，而元素是否出现在用户的可视区域实际上受以下因素的限制（目前已知，待补充） :

 

1. 窗口 ( [viewport](http://www.w3.org/TR/CSS2/visuren.html#viewport) ) 限制，随浏览器滚动条变化
2. 自身是否使用了脱离文档流的定位 ( [absolute fixed](http://www.w3.org/TR/CSS2/visuren.html#choose-position) )
3. 父（祖先）元素是否定位
4. 父（祖先）元素包括祖先元素是否设置了 [overflow != visible](http://www.w3.org/TR/CSS2/visufx.html#overflow-clipping) ，限制了子孙元素的展现

   我想要做的事情就是根据以上因素，确定可供元素展现的可视矩阵，后期再通过移动或缩放尽量智能得将元素放在这个矩阵内.

 

 

例如:

 

![](http://dl.iteye.com/upload/attachment/517354/dbaf06e1-392b-3e58-b34e-033122bd4e2c.png)

 

A 为窗口 ，B 为 overflow:hidden position:static 的处于 A 内的容器，C 为 overflow:auto position:static 的处于 B 内的容器，那么 c 中 position:static 元素的可视矩阵只能为三者交叉的折线处，但如果考虑 c 中 position:absolute 的元素或者如果 c 本身为 overflow:visible ，则情况又有所不同.

1. 对于 c 中 position:absolute 的元素，可视矩阵不受 b c 影响，直接为当前窗口 viewport，随浏览器滚动条变化而变化.
2. 如果 c 为 overflow:visible 则 c 中 position:static 元素的可视矩阵和 c 无关 ，实际为 A,B 相交

 

## 实现：

 

a. 找到可以限制该元素的父（祖先元素），起先想用 offsetParent ([msdn](http://msdn.microsoft.com/en-us/library/ms534302%28VS.85%29.aspx) , [mdc](https://developer.mozilla.org/en/DOM/element.offsetParent) )，但由于需要考虑 overflow 以及ie下的不兼容，放弃！

 

1. 当前元素脱离了文档流，则找祖先定位并设置了 overflow!=visible 的元素
2. 如果元素为 static，则找到设置了 overflow!=visible 的祖先元素

 

b. 通过 a 找到可以限制自己的一个祖先元素后，限定范围为目前祖先元素的当前的可视区域 ([top](http://www.w3.org/TR/cssom-view/#the-getclientrects-and-getboundingclient) ,left,[clientWidth](http://www.w3.org/TR/cssom-view/#client-attributes) ,clientHeight)，如果祖先元素直接为 body 或找不到则限定范围为浏览器 viewport 并结束.

 

c. 重复 a ，通过求交集进一步限定范围

 

d. 最后再次对浏览器 viewport 求交集

 

 

## demo:

 

[visual rect computation @ google code](http://lite-ext.googlecode.com/svn/trunk/lite-ext/playground/visual_rect/getVisibleRectForElement.html?2)

 

可以滚动浏览器，点击文档获得焦点后，按键 1 到 6 来高亮对应 1 - 6 元素的可视矩阵.