因为最近用到了遮罩层和弹出框,上网查资料后自己完成了一个,在此做一下记录做保存。
因为用到了jq,所以需要引入jq文件,比如jquery-1.11.3.js
以下是jsp的代码:
<body>
<div>
<input id="button" type="button" value="点击我">
<div class="shareDialog">
<div class="dialog-top">
<span>移动</span><a class="home-btn-close">×</a>
</div>
<div class="shareDialogChild">hello world</div>
</div>
</div>
<div class="backscreen"></div>
</body>
以下是css文件的代码:
/** 弹出框 **/
.shareDialog{
400px;
height: 400px;
left: 167px;
top: 42.5px;
z-index: 2000;
position: absolute;
background: #fff;
border: 3px solid #95B8E7;
display: none;
}
/** 弹出框顶部蓝色部分 **/
.dialog-top{
cursor: move !important;
400px;
height: 35px;
position: absolute;
left: 0;
top: 0;
font-size: 12px;
background-color: #95B8E7;
z-index: 999;
}
.shareDialogChild{
400px;
height: 400px;
overflow: auto;
}
.home-btn-close{
position: absolute;
top: 5px;
right: 10px;
25px;
height: 25px;
line-height: 25px;
text-align: center;
vertical-align: middle;
font-size: 30px;
color: #333;
background: transparent;
border-radius: 50%;
cursor: pointer;
font: normal 25px/25px "Helvetica Neue", Hevetica Arial,sans-serif;
border: none;
-wekit-transition: background-color .2s ease;
-o-transition: background-color .2s ease;
-moz-transition: background-color .2s ease;
transition: background-color .2s ease;
}
/** 遮罩层 **/
.backscreen{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 999;
background-color: #000;
opacity: 0.75;
display: none;
}
以下是js文件的代码:
$(function(){
$("#button").click(function(){
$(".backscreen").show();
$(".shareDialog").css("display","block");
});
initPosition();
dragAndDrop();
$(".dialog-top .home-btn-close").click(function(e){
$(".shareDialog").hide();
$(".backscreen").hide();
});
});
/**
* 弹出框拖拽
*/
function dragAndDrop(){
var _move = false;
var _x,_y;
$('.dialog-top').mousedown(function(e){
_move = true;
_x = e.pageX - parseInt($(".shareDialog").css("left"));
_y = e.pageY - parseInt($(".shareDialog").css("top"));
});
$(document).mousemove(function(e){
if(_move){
var x = e.pageX - _x;
var y = e.pageY - _y;
$(".shareDialog").css({
top: y,
left: x
});
}
}).mouseup(function(){
_move = false;
});
}
/**
* 初始化拖拽弹出框div的位置
*/
function initPosition(){
//计算初始化位置
var itop = ($(document).height() - $(".shareDialog").height()) / 10;
var ileft = ($(document).width() - $(".shareDialog").width()) / 8;
//设置被拖拽div的位置
$(".shareDialog").css({
top: itop,
left: ileft
});
}
运行后的效果图如下:
点击左上角的“点击我”,就是弹出遮罩层和弹出,可以点击弹出框顶部的蓝色部分,对弹出框进行拖动,点击右上角的时候会关闭弹出来和遮罩层。