通过今天的jquery实例学习,我们要达到这样的效果:点击页面的链接,弹出一个div层,同时页面的其他部分变灰并且不能点击;无论是改变浏览器窗口大小还是下拉滚动条,这个弹出层都能始终保持居中;点击页面的关闭按钮,弹出层消失,页面恢复原样。
这里借鉴之前的一篇文章《基于jQuery的固定飘浮层》,使弹出窗口可以始终固定在浏览器的正中间。在这里有一个要点,就是如何使页面的其他地方在弹出窗口的同时变灰。我使用的方法就是在点击链接弹出div层的时候,给页面增加一个div层,这个层就“负责”使页面变灰。点击关闭后,删除这个层就能使页面恢复原样。不知道有没有更好的方法,有的话请告诉我哦。
其他应该没什么问题了,还是很简单的,在这里顺便贴上jQuery代码:
$(function(){
var screenwidth,screenheight,mytop,getPosLeft,getPosTop
screenwidth = $(window).width();
screenheight = $(window).height();
//获取滚动条距顶部的偏移
mytop = $(document).scrollTop();
//计算弹出层的left
getPosLeft = screenwidth/2 - 260;
//计算弹出层的top
getPosTop = screenheight/2 - 150;
//css定位弹出层
$("#box").css({"left":getPosLeft,"top":getPosTop});
//当浏览器窗口大小改变时...
$(window).resize(function(){
screenwidth = $(window).width();
screenheight = $(window).height();
mytop = $(document).scrollTop();
getPosLeft = screenwidth/2 - 260;
getPosTop = screenheight/2 - 150;
$("#box").css({"left":getPosLeft,"top":getPosTop+mytop});
});
//当拉动滚动条时...
$(window).scroll(function(){
screenwidth = $(window).width();
screenheight = $(window).height();
mytop = $(document).scrollTop();
getPosLeft = screenwidth/2 - 260;
getPosTop = screenheight/2 - 150;
$("#box").css({"left":getPosLeft,"top":getPosTop+mytop});
});
//点击链接弹出窗口
$("#popup").click(function(){
$("#box").fadeIn("fast");
//获取页面文档的高度
var docheight = $(document).height();
//追加一个层,使背景变灰
$("body").append("
$("#greybackground").css({"opacity":"0.5","height":docheight});
return false;
});
//点击关闭按钮
$("#closeBtn").click(function() {
$("#box").hide();
//删除变灰的层
$("#greybackground").remove();
return false;
});
});
html代码:
jquery pop up* {margin:0;padding:0;}
#wrapper {height:1000px;}
#box {display:none;position:absolute;width:520px;height:300px;border:#f60 solid 2px;z-index:200;background:#fff;}
#closeBtn {position:absolute;right:10px;top:10px;cursor:pointer;}
#greybackground {background:#000;display:block;z-index:100;width:100%;position:absolute;top:0;left:0;}
关闭
以上所述是小编给大家介绍的jQuery实现弹出窗口弹出div层的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!