offsetLeft和offsetTop的定位机制
2015-08-06 16:37
323 查看
offsetLeft和offsetTop
表示相对于最近的祖先定位元素(CSS position 属性被设置为
下面的例子中,初次进页面,点击第一个按钮,返回的偏移距离时相对于html文档左上角的偏移值;
第二个按钮则是相对于div,因为将他的父元素div的position属性设为了relative
第三个和第四个则都是相对于body定位
在这个例子中,页面是没有任何定位元素,于是,点击按钮后返回的就是
另外,在IE和Opera浏览器下,
表示相对于最近的祖先定位元素(CSS position 属性被设置为
relative、
absolute或
fixed的元素)的左右偏移值
下面的例子中,初次进页面,点击第一个按钮,返回的偏移距离时相对于html文档左上角的偏移值;
第二个按钮则是相对于div,因为将他的父元素div的position属性设为了relative
第三个和第四个则都是相对于body定位
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> </style> <script> window.onload = function () { }; </script> </head> <body> <div id="div1"> <input id="btn1" type="button" value="父元素为默认定位的时候"/> <br/> <input id="btn2" type="button" value="应用父元素为relative"/> <br/> <input id="btn3" type="button" value="自己定位为relative"/> <br/> <input id="btn4" type="button" value="自己定位为absolute"/> </div> <script> var oBtn1 = document.getElementById('btn1'); oBtn1.onclick = function () { alert(this.offsetParent.tagName); alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop); }; var oBtn2 = document.getElementById('btn2'); oBtn2.onclick = function () { document.getElementById('div1').style.position = 'relative'; this.value = "应用成功"; alert(this.offsetParent.tagName); alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop); }; var oBtn3 = document.getElementById('btn3'); oBtn3.onclick = function () { this.style.position = "relative"; this.style.left = 20+'px'; this.style.top = 20+'px'; alert(this.offsetParent.tagName); alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop); }; var oBtn4 = document.getElementById('btn4'); oBtn4.onclick = function () { this.style.position = "absolute"; this.style.left = 20+'px'; this.style.top = 20+'px'; alert(this.offsetParent.tagName); alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop); }; </script> </body> </html>
offsetParent元素只可能是下面这几种情况:
<body>
position不是
static的元素
<table>,
<th>或
<td>,但必须要
position: static。
在这个例子中,页面是没有任何定位元素,于是,点击按钮后返回的就是
body标签了。
body元素为定位元素的终极boss,所以其上头就没有其他定位元素了。也就是说
body元素没有
offsetParent(尽管有时候
html进入
offsetParent链)。
另外,在IE和Opera浏览器下,
position: fixed的元素没有
offsetParent
相关文章推荐
- 网站权重提高技巧
- Tomcat内存溢出的三种情况及解决办法分析
- subprocess.Popen()详解
- 反网站跟踪的原理
- apache压力测试
- 在NVIDIA GPU 上开发 openCL
- MyEclipse + Tomcat项目重命名
- Openjudge1487 Highways(prim)
- Eclipse里Tomcat启动贼慢的解决方法
- tomcat参考文章
- linux内核日志 dmesg 出现的提示及含意
- nginx php-fpm记录php错误日志怎么配置
- 正向代理与反向代理
- 配置环境变量 解决tomcat启动闪退现象
- OpenCV ——遍历图像方法
- nginx限制某个IP同一时间段的访问次数
- ZooKeeper监控
- 《鸟哥的Linux私房菜》学习Shell部分(2)
- 为Python配置caffe(基于linux)
- Linux 磁盘挂载共享