jQuery Dialog 弹出层对话框插件
2024-05-06 14:27:46
供稿:网友
原理很简单,通过JS动态构建一个div层,将其插入到body中,然后通过调整position的CSS属性为absolute或fixed,使其脱离原来的文档流的位置。再通过适当的加工美化就成了。
代码如下:
<!-- 背景遮盖层 -->
<div class="dialog-overlay"></div>
<!-- 对话框 -->
<div class="dialog">
<div class="bar">
<span class="title">标题</span>
<a class="close">[关闭]</a>
</div>
<div class="content">内容部分</div>
</div>
这就是两个div层的结构,第一个背景遮盖层只有在需要的时候才创建。每个div都定义了一个CSS类,这样便于自定义其外观。
一些基本功能的实现
移动框体
只要在mousemove事件中,计算两次移动鼠标位置的差值,再加上被移动框的原始的top,left,就是对话框新的位置。mousemove事件只需要在鼠标按下标题栏的时候才需要触发,所以只有在触发标题栏的mousedown事件时才绑定mousemove事件,而鼠标释放时也同时解除mousemove的绑定。
mousemove和解除绑定mousemove事件的mouseup却没有绑定到标题栏上,而是document上,之所以这样,是因为有时鼠标移动过快时,会移出标题栏范围,此时若是绑定到标题栏上的事件就会失效,而绑定到document就不会。
代码如下:
var mouse={x:0,y:0};
function moveDialog(event)
{
var e = window.event || event;
var top = parseInt(dialog.css('top')) + (e.clientY - mouse.y);
var left = parseInt(dialog.css('left')) + (e.clientX - mouse.x);
dialog.css({top:top,left:left});
mouse.x = e.clientX;
mouse.y = e.clientY;
};
dialog.find('.bar').mousedown(function(event){
var e = window.event || event;
mouse.x = e.clientX;
mouse.y = e.clientY;
$(document).bind('mousemove',moveDialog);
});
$(document).mouseup(function(event){
$(document).unbind('mousemove', moveDialog);
});
定位
居中定位很容易实现,IE下的clientWidth, offsetWidth等一系列属性和其它浏览器好像有点不一样,所以不要用这些属性,可以直接用jQuery下的width()函数:
代码如下:
var left = ($(window).width() - dialog.width()) / 2;
var top = ($(window).height() - dialog.height()) / 2;
dialog.css({top:top,left:left});IE6下并没有fixed模式,但是能通过window.onscroll事件模拟实现:
// top 对话框到可视区域顶部位置的距离。
var top = parseInt(dialog.css('top')) - $(document).scrollTop();
var left = parseInt(dialog.css('left')) - $(document).scrollLeft();
$(window).scroll(function(){
dialog.css({'top':$(document).scrollTop() + top,'left':$(document).scrollLeft() + left});
});
z-index
为了能实现多个对话框并存,采用了一个静态的zIndex变量,每次创建新对话框时,都实现一次自增操作,并将新值赋值给新创建的对话框的z-index,这样就能保证最后创建的对话框总在最前面。