html 弹出div 居中 可移动

本文介绍了一个使用JavaScript实现的可拖动并能自动居中的HTML弹窗。该弹窗具备显示、隐藏功能,并可通过头部进行拖拽定位。文章提供了完整的代码示例,演示了如何利用JavaScript获取窗口尺寸、元素位置等信息,以实现元素的精确控制。
<!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>
<style type="text/css">
.show,.hide{
	position:absolute;
	width:200px;
	height:200px;
	border:5px solid #ccc;
	background-color:red;
	font-size:14px;
	font-weight:bold;
	padding:5px;
	text-align:center;
	color:#a24;
}

.hide{
	display:none;
}

#header{
	width:80%;
	height:8px;
	background-color:#AAAAAA;
	cursor:move;
	float:left;
}
</style>
</head>

<body>
<div id="c" class="hide">
	<div>
		<div id="header">Title</div>
		<div id="close" style="float:right;background-color:#FFFFFF;">Close</div>
	</div>
通过JS控制层绝对居中
</div>
<div style="width:500px;height:1000px;background-color:#FFFFFF;"></div>
<div onclick="show();">点我</div>
<SCRIPT LANGUAGE="JavaScript">
	var a = document.getElementById("c");
	var header = document.getElementById("header");
	var oClose = document.getElementById("close");
	var bDrag = false;
	var disX = disY = 0;

   function show(){
	   var scrollTop = window.pageYOffset  
                || document.documentElement.scrollTop  
                || document.body.scrollTop  
                || 0;

		a.className = "show";
		a.style.left=(document.documentElement.clientWidth/2-a.clientWidth/2)+"px";
		a.style.top=(scrollTop+document.documentElement.clientHeight/2-a.clientHeight/2)+"px";
	    
   }

	oClose.onclick = function ()
	{
		a.className = "hide";
		
	};
	oClose.onmousedown = function (event)
	{
		(event || window.event).cancelBubble = true;
	};

	header.onmousedown = function (event)
	{		
		var event = event || window.event;
		bDrag = true;
		disX = event.clientX - a.offsetLeft;
		disY = event.clientY - a.offsetTop;		
		this.setCapture && this.setCapture();		
		return false
	};
	document.onmousemove = function (event)
	{
		if (!bDrag) return;
		var event = event || window.event;
		var iL = event.clientX - disX;
		var iT = event.clientY - disY;
		var maxL = document.documentElement.clientWidth - a.offsetWidth;
		var maxT = document.documentElement.clientHeight - a.offsetHeight;		
		iL = iL < 0 ? 0 : iL;
		//iL = iL > maxL ? maxL : iL; 		
		iT = iT < 0 ? 0 : iT;
		//iT = iT > maxT ? maxT : iT;
		
		a.style.marginTop = a.style.marginLeft = 0;
		a.style.left = iL + "px";
		a.style.top = iT + "px";		
		return false
	};
	document.onmouseup = window.onblur = header.onlosecapture = function ()
	{
		bDrag = false;
		header.releaseCapture && header.releaseCapture();
	};
</SCRIPT> 
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值