以下是使用jQuery實現可拖動的浮動層的完整代碼,復制保存到html文件就可以體驗效果。
<!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>
<title>jQuery實現可拖動的浮動層 - </title>
<style type="text/css">
body,a{ padding:0; margin:0;}
.Pop_Layer{ width:500px; top:400px; left:280px; position:absolute; z-index:10; background-color:#ABABAB; border:2px #8989DD solid; font-family:@微軟雅黑; font-size:20px; }
.Pop_Head{ height:25px; width:100%; text-align:right; background:#888888; line-height:25px;}
.Pop_Head a{ margin-right:2px; color:Black; background-color:#999999; text-decoration:none;}
.Pop_Content{ padding:15px 20px;}
.Pop_Foot{ padding:5px 100px}
.Pop_Foot input{ margin:0px 10px; height:25px;}</style>
<script type="text/javascript" src="http:///keleyi/pmedia/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
var defaultx;
var defaulty;
var objx;
var objy;
var posx;
var poxy;
var IsKeydown = 0;
function M_Keydown(e) {
IsKeydown = 1;
$(".Pop_Layer").css("cursor", "move");
defaultx = e.pageX;
defaulty = e.pageY;
objx = $(".Pop_Layer")[0].offsetLeft;
objy = $(".Pop_Layer")[0].offsetTop;
};
function M_Keyup() {
IsKeydown = 0;
$(".Pop_Layer").css("cursor", "default");
};
function M_Move(ee) {
if (!ee) ee = window.event;
if (IsKeydown == 1) {
$(".Pop_Layer").css("left", objx + ee.pageX - defaultx);
$(".Pop_Layer").css("top", objy + ee.pageY - defaulty);
}
else return;
};
function PopClose() {
$(".Pop_Layer").css("display", "none");
}
</script>
<script type="text/javascript">
$(function () {
$("a#A_ShowHideDiv").click(function () {
$(".Pop_Layer").css("display", "block");
});
$(".Pop_Head").mousedown(M_Keydown);
$(".Pop_Head").mousemove(M_Move);
$(".Pop_Head").mouseup(M_Keyup);
$("div.Pop_Head > a").click(PopClose);
$("#PopBtnOK").click(function () {
location = "http://";
});
$("#PopBtnCancel").click(PopClose);
})
</script>
</head>
<body>
<div><a id="A_ShowHideDiv" href="#">顯示可拖動浮動層</a></div>
<div class="Pop_Layer">
<div class="Pop_Head">
<a href="#">X</a>
</div>
<div class="Pop_Content">
層的內容<br />
this is the content area.<br />
visit<br />
www.<br />
this is the content area.<br />
<br />
</div>
<div class="Pop_Foot">
<input type="button" id="PopBtnOK" value="確定" />
<input type="button" id="PopBtnCancel" value="取消" />
</div>
</div>
</body>
</html>