兼容主流浏览器的jQuery+CSS实现遮罩层的简单代码
在页面点击"注册",出现一层有不透明度的黑色遮罩;遮罩层的上方是注册框;此时无法点击页面上除注册框外的其他元素;点击注册框上的"随便逛逛",遮罩层消失。
预览地址:
http://jsfiddle.net/p2x3c7df/embedded/result/
要点:
1.注册框始终水平、垂直居中,包括鼠标滚轮上下滚动页面、缩放页面和调整浏览器窗口大小时
主要由CSS控制,注册框的宽度和高度都已经确定(620*420px),首先使用position:fixed来使它相对于浏览器窗口绝对定位;然后使它垂直居中:top:50%;left:50%;margin:-210px00-310px;
2.当缩放页面和调整浏览器窗口大小时,遮罩层需始终覆盖整个文档和充满整个浏览器可视窗口以及需要滚动才能浏览到的部分,需要兼容Chrome和IE等不同内核浏览器;
两个重要的属性:js的window.screen.availHeight和jQuery的$(document.body).outerHeight(true)。window.screen.availHeight指屏幕可用工作区域的高,$(document.body).outerHeight(true)指浏览器当前窗口文档body的总宽度包括borderpaddingmargin。window.screen.availHeight主要用于IE(11)缩放页面后,遮罩层仍能充满浏览器窗口。
3.遮罩层出现时,页面仍可以上下滚动,但是无法操作页面中除登陆框外的其他元素
代码:
HTML(需测试足够高的文档):
<divid="wrap">
<divid="rbox"><aclass="go"href="#"onclick="returnfalse;">先逛逛>></a></div>
<divid="mask"></div>
<divclass="content">
<divid="usertie">
<span>
<aid="register"href="#"onclick="returnfalse;">注册</a>
</span>
</div>
TheSuicide.
MeanwhileMonteCristohadalsoreturnedtotownwithEmmanuelandMaximilian.Theirreturnwascheerful.Emmanueldidnotconcealhisjoyatthepeacefulterminationoftheaffair,andwasloudinhisexpressionsofdelight.Morrel,inacornerofthecarriage,allowedhisbrother-in-law"sgayetytoexpenditselfinwords,whilehefeltequalinwardjoy,which,however,betrayeditselfonlyinhiscountenance.AttheBarriereduTronetheymetBertuccio,whowaswaitingthere,motionlessasasentinelathispost.MonteCristoputhisheadoutofthewindow,exchangedafewwordswithhiminalowtone,andthestewarddisappeared."Count,"saidEmmanuel,whentheywereattheendofthePlaceRoyale,"putmedownatmydoor,thatmywifemaynothaveasinglemomentofneedlessanxietyonmyaccountoryours."
"Ifitwerenotridiculoustomakeadisplayofourtriumph,Iwouldinvitethecounttoourhouse;besidesthat,hedoubtlesshassometremblinghearttocomfort.Sowewilltakeleaveofourfriend,andlethimhastenhome."
"Stopamoment,"saidMonteCristo;"donotletmelosebothmycompanions.Return,Emmanuel,toyourcharmingwife,andpresentmybestcomplimentstoher;anddoyou,Morrel,accompanymetotheChampsElysees."
"Willingly,"saidMaximilian;"particularlyasIhavebusinessinthatquarter."
"Shallwewaitbreakfastforyou?"askedEmmanuel.
"No,"repliedtheyoungman.Thedoorwasclosed,andthecarriageproceeded."SeewhatgoodfortuneIbroughtyou!"saidMorrel,whenhewasalonewiththecount."Haveyounotthoughtso?"
"Yes,"saidMonteCristo;"forthatreasonIwishedtokeepyounearme."
"Itismiraculous!"continuedMorrel,answeringhisownthoughts.
"What?"saidMonteCristo.
"Whathasjusthappened."
"Yes,"saidtheCount,"youareright--itismiraculous."
"ForAlbertisbrave,"resumedMorrel.
"Verybrave,"saidMonteCristo;"Ihaveseenhimsleepwithaswordsuspendedoverhishead."
"Sheisgoingtoleaveherhouse,"saidthesteward.
"Andherson?"
"Florentin,hisvalet,thinksheisgoingtodothesame."
"Comethisway."MonteCristotookBertucciointohisstudy,wrotetheletterwehaveseen,andgaveittothesteward."Go,"saidhequickly."Butfirst,letHaideebeinformedthatIhavereturned."
"HereIam,"saidtheyounggirl,whoatthesoundofthecarriagehadrundown-stairsandwhosefacewasradiantwithjoyatseeingthecountreturnsafely.Bertuccioleft.Everytransportofadaughterfindingafather,allthedelightofamistressseeinganadoredlover,werefeltbyHaideeduringthefirstmomentsofthismeeting,whichshehadsoeagerlyexpected.Doubtless,althoughlessevident,MonteCristo"sjoywasnotlessintense.Joytoheartswhichhavesufferedlongislikethedewonthegroundafteralongdrought;boththeheartandthegroundabsorbthatbeneficentmoisturefallingonthem,andnothingisoutwardlyapparent.
MonteCristowasbeginningtothink,whathehadnotforalongtimedaredtobelieve,thatthereweretwoMercedesintheworld,andhemightyetbehappy.Hiseye,elatewithhappiness,wasreadingeagerlythetearfulgazeofHaidee,whensuddenlythedooropened.Thecountknithisbrow."M.deMorcerf!"saidBaptistin,asifthatnamesufficedforhisexcuse.Infact,thecount"sfacebrightened.
"Which,"askedhe,"theviscountorthecount?"
"Thecount."
"Oh,"exclaimedHaidee,"isitnotyetover?"
"Iknownotifitisfinished,mybelovedchild,"saidMonteCristo,takingtheyounggirl"shands;"butIdoknowyouhavenothingmoretofear."
"Butitisthewretched"--
"Thatmancannotinjureme,Haidee,"saidMonteCristo;"itwashissonalonethattherewascausetofear."
"AndwhatIhavesuffered,"saidtheyounggirl,"youshallneverknow,mylord."MonteCristosmiled."Bymyfather"stomb,"saidhe,extendinghishandovertheheadoftheyounggirl,"Isweartoyou,Haidee,thatifanymisfortunehappens,itwillnotbetome."
Thedoorwaswideopen,ahackney-coachwasstandinginthemiddleoftheyard--astrangesightbeforesonobleamansion;thecountlookedatitwithterror,butwithoutdaringtoinquireitsmeaning,herushedtowardshisapartment.Twopersonswerecomingdownthestairs;hehadonlytimetocreepintoanalcovetoavoidthem.ItwasMercedesleaningonherson"sarmandleavingthehouse.Theypassedclosebytheunhappybeing,who,concealedbehindthedamaskcurtain,almostfeltMercedesdressbrushpasthim,andhisson"swarmbreath,pronouncingthesewords,--"Courage,mother!Come,thisisnolongerourhome!"Thewordsdiedaway,thestepswerelostinthedistance.Thegeneraldrewhimselfup,clingingtothecurtain;heutteredthemostdreadfulsobwhicheverescapedfromthebosomofafatherabandonedatthesametimebyhiswifeandson.Hesoonheardtheclatteroftheironstepofthehackney-coach,thenthecoachman"svoice,andthentherollingoftheheavyvehicleshookthewindows.Hedartedtohisbedroomtoseeoncemoreallhehadlovedintheworld;butthehackney-coachdroveonandtheheadofneitherMercedesnorhersonappearedatthewindowtotakealastlookatthehouseorthedesertedfatherandhusband.Andattheverymomentwhenthewheelsofthatcoachcrossedthegatewayareportwasheard,andathicksmokeescapedthroughoneofthepanesofthewindow,whichwasbrokenbytheexplosion.
Thedoorwaswideopen,ahackney-coachwasstandinginthemiddleoftheyard--astrangesightbeforesonobleamansion;thecountlookedatitwithterror,butwithoutdaringtoinquireitsmeaning,herushedtowardshisapartment.Twopersonswerecomingdownthestairs;hehadonlytimetocreepintoanalcovetoavoidthem.ItwasMercedesleaningonherson"sarmandleavingthehouse.Theypassedclosebytheunhappybeing,who,concealedbehindthedamaskcurtain,almostfeltMercedesdressbrushpasthim,andhisson"swarmbreath,pronouncingthesewords,--"Courage,mother!Come,thisisnolongerourhome!"Thewordsdiedaway,thestepswerelostinthedistance.Thegeneraldrewhimselfup,clingingtothecurtain;heutteredthemostdreadfulsobwhicheverescapedfromthebosomofafatherabandonedatthesametimebyhiswifeandson.Hesoonheardtheclatteroftheironstepofthehackney-coach,thenthecoachman"svoice,andthentherollingoftheheavyvehicleshookthewindows.Hedartedtohisbedroomtoseeoncemoreallhehadlovedintheworld;butthehackney-coachdroveonandtheheadofneitherMercedesnorhersonappearedatthewindowtotakealastlookatthehouseorthedesertedfatherandhusband.Andattheverymomentwhenthewheelsofthatcoachcrossedthegatewayareportwasheard,andathicksmokeescapedthroughoneofthepanesofthewindow,whichwasbrokenbytheexplosion.
</div>
</div>
HTML
CSS:
a{text-decoration:none;color:#fff;}
#rbox{
width:620px;
height:420px;
position:fixed;
top:50%;
left:50%;
margin:-210px00-310px;
border-radius:8px;/*圆角*/
background-color:#999;
z-index:3;
display:none;
}
.go{
position:absolute;
right:10px;
top:10px;
padding:5px12px;
background:rgba(0,0,0,.4);
box-shadow:0002pxrgba(255,255,255,.4);
color:#fff;
border-radius:26px;
}
#mask{
background-color:#000;
position:absolute;
top:0;
left:0;
display:none;
z-index:2;
}
#register{z-index:1;color:blue;}
.content{width:800px;height:auto;margin:0auto;}
JS:
//根据浏览器窗口变化改变遮罩宽度和高度,使遮罩充满整个浏览器 $("#mask").css("width","100%");//必要时可对宽度也作出判断 if(window.screen.availHeight>$(document.body).outerHeight(true)){ $(".go").click(function(){ 至此功能完成。
$(function(){
//点击注册
$("#register").click(function(){
if(window.screen.availHeight>$(document.body).outerHeight(true)){
//当屏幕可用工作区域的高度>浏览器当前窗口文档body的总高度包括borderpaddingmargin时(缩放时)
$("#mask").show().css({"opacity":"0.5","width":"100%","height":window.screen.availHeight});
}else{
$("#mask").show().css({"opacity":"0.5","width":"100%","height":$(document.body).outerHeight(true)});
}
$("#rbox").show();
});
//根据浏览器可视窗口的变化调整遮罩的宽度和高度,使遮罩充满浏览器
$(window).resize(function(){
if($("#mask").css("width")!=0){
$("#mask").css({"opacity":"0.5","width":"100%","height":window.screen.availHeight});
}else{
$("#mask").css({"opacity":"0.5","width":"100%","height":$(document.body).outerHeight(true)});
}
}
});
$("#mask").hide();
$("#rbox").hide();
});
});
相关文章