获取DOM节点位置,将js生成的div插入到指定的节点处
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>获取DOM节点位置,将js生成的div插入到指定的节点处</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
.object{
margin:30px 0px 0px 100px;
width:500px;
height:260px;
position:relative;
border:#CCCCCC 1px solid;
background-color:#FFFFFF;
}
.object p{
width:100px;
height:100px;
background-color:#330000;
display:block;
position:absolute;
top:10px;
left:10px;
}
li{
width:110px;
height:100px;
line-height:100px;
text-align:center;
border:#CCCCCC 1px solid;
float:left;
margin-left:10px;
margin-top:20px;
display:inline;
}
</style>
</head>
<body onload="pos();">
<div class="object" id="object">
<ul>
<li>li元素</li>
<li>li元素</li>
<li>li元素</li>
<li>li元素</li>
<li>li元素</li>
<li>li元素</li>
<li>li元素</li>
<li id="aa">li元素</li>
</ul>
</div>
<input type="button" value="确定" onclick="aa();"/><!--单击获取指定元素相对于整个文档的X,Y位置;-->
<script type="text/javascript">
function pos()
{
var object=document.getElementById("object");
//alert(object.offsetLeft)
var li=object.getElementsByTagName("li");
for(i=0;i<li.length;i++)
{
li[i].onmouseover=function()
{
//alert(this.offsetLeft);
//alert(this.offsetTop);
this.style.position="relative";
popbox(this);
var correct=this.lastChild.offsetWidth-this.offsetWidth;//弹出层超出父级宽度范围时,计算纠正值;
if(this.offsetLeft+150>500)
{
this.lastChild.style.left=-correct+"px";
}
}
li[i].onmouseout=function()
{
this.style.position="";
if(this.lastChild.className=="newdiv"){//如果元素的class是newdiv,则将其移除;
this.removeChild(this.lastChild);
}
}
}
}
function popbox(id)
{
var newdiv=document.createElement("div");
newdiv.style.position="absolute";
newdiv.style.top="100px";
newdiv.style.left="0px";
newdiv.style.height="50px";
newdiv.style.width="150px";
newdiv.style.backgroundColor="#fff000"
newdiv.className="newdiv"
id.appendChild(newdiv);//将生成的div层插入到指定的节点内,成为其最后一个子节点;
}
function aa(){
var aa=document.getElementById("aa");
alert(pageX(aa))
alert(pageY(aa))
}
function pageX(elem) {//获取元素相对于整个文档的X位置的函数;
var p = 0;
while ( elem.offsetParent ) {
p += elem.offsetLeft;
elem = elem.offsetParent;
}
return p;
}
function pageY(elem){ //获取元素相对于整个文档的Y位置的函数;
var p = 0;
while ( elem.off