首页 > 技术文章 > js相对定位

hnbiao 2016-02-19 17:12 原文

效果图:



<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Examples</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> <style> </style> </head> <body> <div style="width:1200px;height:120px;background:red;" id="div1">aaaaaaaaaaaaaaaa</div> <div style="width:1200px;height:120px;background:green;">aaaaaaaaaaaaaaaa</div> <div style="width:1200;height:120px;">aaaaaaaaaaaaaaaa</div> <div id="weixin_img"> <img src="weixin.jpg" alt="" style="width:130px;"> </div> <div style="width:1200px;height:1200px;background:green;">aaaaaaaaaaaaaaaa</div> </body> <script> var div1=document.getElementById('div1'); /*获取元素的纵坐标*/ function getTop(e) { var offset=e.offsetTop; if(e.offsetParent!=null){ offset+=getTop(e.offsetParent); } return offset; } /*获取元素的横坐标*/ function getLeft(e) { var offset=e.offsetLeft; if(e.offsetParent!=null){ offset+=getLeft(e.offsetParent); } return offset; } document.getElementById('weixin_img').style.position="fixed"; document.getElementById('weixin_img').style.top=getTop(div1)+"px"; document.getElementById('weixin_img').style.left=(getLeft(div1)+1200)+"px"; </script> </html>

 

推荐阅读