您的位置:首页 > Web前端 > JavaScript

DIV弹出层练习(一) ------------------ 用js实现在超链接的下方弹出div层

2010-08-14 21:47 337 查看
实现思想主要是通过函数getAbsolutePos取得超连接的坐标,然后将其纵坐标加15,横坐标不变,以此坐标设置弹出div的top和left的属性,最后将新建的div通过document.body.appendChild加入到页面中,另外注意的是新弹出的div显示到前面是由于设置了其style的zIndex属性,这个很重要。
<html>
<head>
<title>用js实现在超链接中的下方弹出div层</title>
<script type="text/javascript">
<!--
//取得组件
function $(id){
return document.getElementById(id);
}
//id是新层id,coverid是覆盖层的id,contentid是新层弹出内容所对应的id,本例没有覆盖层
function openNewDiv(id,coverid,contentid) {
if ($(id)!=null)
document.body.removeChild($(id));
if ($(coverid)!=null)
document.body.removeChild($(coverid));
var r = getAbsolutePos($('zxc'));
// 创建新激活图层
var newDiv = document.createElement("div");
newDiv.id = id;
newDiv.style.position = "absolute";
//让新层的zIndex属性要足够大,才会在最上面显示
newDiv.style.zIndex = "9999";
newDiv.style.width = $(contentid).style.width;
newDiv.style.height = $(contentid).style.height;
//newDiv.style.top = "100px";
//newDiv.style.left = (parseInt(document.body.scrollWidth) - 300) / 2
//  + "px"; // 屏幕居中
newDiv.style.top=r.y+15;
newDiv.style.left=r.x;
newDiv.style.background = "#BBBDBF";
newDiv.style.border = "1px solid #BBBDBF";
newDiv.innerHTML = $(contentid).innerHTML;
document.body.appendChild(newDiv);
}
//移除新层和覆盖层
function removeDiv(id,coverid){
if($(id)!=null)
document.body.removeChild($(id));
if($(coverid)!=null)
document.body.removeChild($(coverid));
return false;
}
//取得组件的坐标
function getAbsolutePos(el)
{
var SL = 0, ST = 0;
var is_div = /^div$/i.test(el.tagName);
if (is_div && el.scrollLeft)
SL = el.scrollLeft;
if (is_div && el.scrollTop)
ST = el.scrollTop;
var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
if (el.offsetParent)
{
var tmp = this.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
}
// --></script>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<center><a id="zxc"style="cursor: pointer;text-decoration: underline;" onclick="openNewDiv('a','b','c')">放入购物车</a></center>
<div id="c" style="display: none;" mce_style="display: none;">
<div
style="border: 2px solid #BBBDBF width : 70; background-color: #BBBDBF">
<p>
你确定要放入购物车吗?
</p>
<br />
<center>
<a style="cursor: pointer; text-decoration: underline;" mce_style="cursor: pointer; text-decoration: underline;"
onclick="alert('success!')" ></a>确定</a>
<a style="cursor: pointer; text-decoration: underline;" mce_style="cursor: pointer; text-decoration: underline;"
onclick="removeDiv('a','b')">取消</a>
</center>
</div>
</div>
</body>
</html>


效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: