jQuery Dialog 弹出层对话框插件
本文采用 知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议 进行许可。
转载时请注明出处:http://www.caixw.com/archives/drop-down-menu-with-css3.html
网上这种插件很多,但是没一个合适的,大部分都做得很大,功能齐全。于是自己做了这个小插件,顺便学习下jQuery插件的写法。
具体的演示程序在这里:演示程序。
原理很简单,通过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});
- });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述