用jQuery實現彈出視窗彈出div層
阿新 • • 發佈:2019-02-02
通過今天的jquery例項學習,我們要達到這樣的效果:點選頁面的連結,彈出一個div層,同時頁面的其他部分變灰並且不能點選;無論是改變瀏覽器視窗大小還是下拉滾動條,這個彈出層都能始終保持居中;點選頁面的關閉按鈕,彈出層消失,頁面恢復原樣。
這裡借鑑之前的一篇文章《基於jQuery的固定飄浮層》,使彈出視窗可以始終固定在瀏覽器的正中間。在這裡有一個要點,就是如何使頁面的其他地方在彈出視窗的同時變灰。我使用的方法就是在點選連結彈出div層的時候,給頁面增加一個div層,這個層就“負責”使頁面變灰。點選關閉後,刪除這個層就能使頁面恢復原樣。不知道有沒有更好的方法,有的話請告訴我哦。
這裡借鑑之前的一篇文章《基於jQuery的固定飄浮層》,使彈出視窗可以始終固定在瀏覽器的正中間。在這裡有一個要點,就是如何使頁面的其他地方在彈出視窗的同時變灰。我使用的方法就是在點選連結彈出div層的時候,給頁面增加一個div層,這個層就“負責”使頁面變灰。點選關閉後,刪除這個層就能使頁面恢復原樣。不知道有沒有更好的方法,有的話請告訴我哦。
其他應該沒什麼問題了,還是很簡單的,在這裡順便貼上jquery程式碼:
html程式碼:$(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("<div id='greybackground'></div>"); $("#greybackground").css({"opacity":"0.5","height":docheight}); return false; }); //點選關閉按鈕 $("#closeBtn").click(function() { $("#box").hide(); //刪除變灰的層 $("#greybackground").remove(); return false; }); });
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery pop up</title> <script src=http://blog.soso.com/qz.q/"jquery.js" type="text/javascript"></script> <style type="text/css"> * {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;} </style> </head> <body> <div id="wrapper"> <a href=http://blog.soso.com/qz.q/"#" id="popup">點選彈出div視窗</a> </div> <div id="box"> <span id="closeBtn">關閉</span> </div> </body> </html>