1、在html页面中定义一个div,并在div实现我们需要展示的内容。
代码如下:
3、我们需要让它居中展示,那么首先就必须获取浏览器的高度和宽度,如果有滚动条的水平或者竖向偏移,还需要获取那个长度,通过计算获取div应该浏览器的位置。
代码如下:
$(document).ready(function()
{
jQuery.fn.extend({
center:function(width,height)
{
return $(this).css("left", ($(window).width()-width)/2+$(window).scrollLeft()).
css("top", ($(window).height()-height)/2+$(window).scrollTop()).
css("width",width).
css("height",height);
}
});
});
通过点击按钮让它展现
代码如下:
$(".login").click(function ()
{
$("#login").show().center(350,250);//展现登陆框
});
效果图
4、能对弹出框进行拖拽
代码实现
代码如下:
$(document).ready(function()
{
jQuery.fn.extend({
//拖拽功能
drag:function(){
var $tar = $(this);
return $(this).mousedown(function(e){
if(e.target.tagName =="H2"){
var diffX = e.clientX - $tar.offset().left;
var diffY = e.clientY - $tar.offset().top;
$(document).mousemove(function(e){
var left = e.clientX - diffX;
var top = e.clientY - diffY;
if (left < 0){
left = 0;
}
else if (left <= $(window).scrollLeft()){
left = $(window).scrollLeft();
}
else if (left > $(window).width() +$(window).scrollLeft() - $tar.width()){
left = $(window).width() +$(window).scrollLeft() -$tar.width();
}
if (top < 0){
top = 0;
}
else if (top <= $(window).scrollTop()){
top = $(window).scrollTop();
}
else if (top > $(window).height() +$(window).scrollTop() - $tar.height()){
top = $(window).height() +$(window).scrollTop() - $tar.height();
}
$tar.css("left",left + 'px').css("top",top + 'px');
});
}
$(document).mouseup(function(){
$(this).unbind("mousemove");
$(this).unbind("mouseup")
});
});
}
});
});
这里我们只针对div内容中的H2元素可供点击拖拽,如果需要全局div可进行修改,拖拽原理:当鼠标在指定元素上的按下时,获取该鼠标点坐标,通过计算,把图片也移动到相对应的位置,一旦鼠标点击取消,相对应的按下事件也随之取消,页面静止。
调用拖拽方法
代码如下:
$("#login").drag();
现在我们可以点击弹出框的标题栏随意对其在浏览器中拖拽了。