仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 873|回复: 8
打印 上一主题 下一主题

[DIV+CSS] 来一发CSS Sprite图片处置技能

[复制链接]
分手快乐 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-16 00:12:47 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
更方便搜索引擎的搜索。用只包含结构化内容的HTML代替嵌套的标签,搜索引擎将更有效地搜索到你的内容,并可能给你一个较高的评价(ranking)。
  在之前我们的事情中,以传统切图头脑举行操纵,考究精密,图片规格越小越好,分量越小越好,实在规格巨细无所谓,盘算机一致都按Byte盘算。
  客户端每显现一张图片城市向服务器发送哀求,以是,图片越多哀求次数越多,形成提早的大概性也就越年夜。由于一张图片的传输工夫,一般远小于哀求守候的工夫。
  典范如文本编纂器,小图标出格多,翻开时一张张跑出来,给用户的感到很欠好。假如能用一张图办理,则不会有这个成绩,好比百度空间、163博客、Gmail都是这么做的,poluoluo.com也倡始如许的操纵办法。

CSSSprites:ImageSlicing’sKissofDeath
Backwhenvideogameswerestillfun(we’retalkingaboutthe8-bitglorydayshere),graphicswereamuchsimplermatterbynecessity.Bitmapped2-dimensionalcharacterdataandbackgroundscenerywasindividuallydrawn,muchliketoday’sresurgentpixelart.Hundredsandlaterthousandsofsmallgraphicscalledspriteswerethebuildingblocksforallthingsvisualinagame.

Asgamecomplexityincreased,techniquesdevelopedtomanagethemultitudeofspriteswhilekeepinggameplayflowing.Onevariationsawspritesbeingpluggedintoamastergrid,thenlaterpulledoutasneededbycodethatmappedpositionsofeachindividualgraphic,andselectivelypaintedthemonthescreen.
Andwhatdoesthishavetodowiththeweb?

Everythingoldisnewagain,andthoughtheriseof3Dgameshasmadespritemapsobsolete,theconcurrentriseofmobiledeviceswith2Dgamingcapabilitieshavebroughtthembackintovogue.Andnow,withabitofmathandalotofCSS,we’regoingtotakethebasicconceptandapplyittotheworldofwebdesign.
Specifically,we’regoingtoreplaceold-schoolimageslicinganddicing(andthenecessaryJavaScript)withaCSSsolution.AndbecauseofthewayCSSworks,we’regoingtotakeitfurther:bybuildingagridofimagesanddevisingawaytogeteachindividualcelloutofthegrid,wecanstoreallbuttons/navigationitems/whateverwewishinasinglemasterimagefile,alongwiththeassociated“before”and“after”linkstates.
HowdoCSSSpriteswork?

Asitturnsout,thebasictoolstodothisarebuiltintoCSS,givenabitofcreativethinking.
Let’sstartwiththemasterimageitself.Dividingarectangleintofouritems,you’llobserveinthismasterimagethatourintended“before"linkimagesareonthetoprow,with“after":hoverstatesimmediatelybelow.There’snocleardivisionbetweenthefourlinksatthemoment,soimaginethateachpieceoftextisalinkfornow.(Forthesakeofsimplicity,we’llcontinuetorefertolinkimagesas“before”imagesandthe:hoverstateas“after”fortherestofthisarticle.It’spossibletoextendthismethodto:active,:focus,and:visitedlinksstatesaswell,butwewon’tgointothathere.)
ThosefamiliarwithPetrStanicek’s(Pixy)FastRolloversmayalreadyseewherewe’regoingwiththis.ThisarticleowesadebtofgratitudetoPixy’sexampleforthebasicfunctionwe’llberelyingon.Butlet’snotgetaheadofourselves.
OntotheHTML.EverygoodCSStrickstrivestoaddalayerofvisualsontopofacleanblockofcode,andthistechniqueisnoexception:
  1. <ulid="skyline"><liid="panel1b"><ahref="#1"></a></li><liid="panel2b"><ahref="#2"></a></li><liid="panel3b"><ahref="#3"></a></li><liid="panel4b"><ahref="#4"></a></li></ul>
复制代码
Thiscodewillserveasabaseforourexample.Light-weight,simplemarkupthatdegradeswellinolderandCSS-disabledbrowsersisalltherage,andit’satrendthat’sgoodfortheindustry.It’sagreatidealtoshootfor.(We’llignoreanytextinsidethelinksforthetimebeing.Applyyourfavoriteimagereplacementtechniquelatertohidethetextyou’llendupadding.)
ApplyingtheCSS

Withthosebasicbuildingblocks,it’stimetobuildtheCSS.Aquicknotebeforewestart—becauseofanIEglitch,we’llbetilingtheafterimageontopofthebeforeimagewhenweneedit,insteadofreplacingonewiththeother.Theresultmakesnorealvisualdifferenceifwelinethemupprecisely,butthismethodavoidswhatotherwisewouldbeanobvious“flicker”effectthatwedon’twant.
  1. #skyline{width:400px;height:200px;background:url(test-3.jpg);margin:10pxauto;padding:0;position:relative;}#skylineli{margin:0;padding:0;list-style:none;position:absolute;top:0;}#skylineli,#skylinea{height:200px;display:block;}
复制代码
Counter-intuitively,we’renotassigningthebeforeimagetothelinksatall,it’sappliedtothe<ul>instead.You’llseewhyinamoment.
TherestoftheCSSintheaboveexamplesetsthingslikethedimensionsofthe#skylineblockandthelistitems,startingpositionsforthelistitems,anditturnsofftheunwantedlistbullets.
We’llbeleavingthelinksthemselvesasempty,transparentblocks(thoughwithspecificdimensions)totriggerthelinkactivity,andpositionthemusingthecontaining<li>s.Ifweweretopositionthelinksthemselvesandeffectivelyignorethe<li>s,we’dstartseeingerrorsinolderbrowsers,solet’savoidthis.
Positioningthelinks

The<li>sareabsolutelypositioned,sowhyaren’ttheyatthetopofthebrowserwindow?Aquirkybutusefulpropertyofpositionedelementsisthatalldescendentelementscontainedwithinthembasetheirabsolutepositionnotoffthecornersofthebrowserwindow,butoffthecornersofthenearestpositionedancestorelement.Theupshotofthisisthatsinceweappliedposition:relative;to#skyline,we’reabletoabsolutelypositionthe<li>sfromthetopleftcornerof#skylineitself.
  1. #panel1b{left:0;width:95px;}#panel2b{left:96px;width:75px;}#panel3b{left:172px;width:110px;}#panel4b{left:283px;width:117px;}
复制代码
So#panel1isn’thorizontallypositionedatall,#panel2bispositioned96pxtotheleftof#skyline’sleftedge,andsoon.Weassignedthelinksadisplay:block;valueandthesameheightasthe<li>sinthepastlisting,sothey’llendupfillingtheircontaining<li>s,whichisexactlywhatwewant.
Atthispointwehaveabasicimagemapwithlinks,butno:hoverstates.Seetheexample.It’sprobablyeasiertoseewhat’shappeningwithbordersturnedon.
Hovers

InthepastwewouldhaveappliedsomeJavaScripttoswapinanewimagefortheafterstate.Insteadourafterstatesareinoneimage,soallweneedisawaytoselectivelypulleachstateoutfortheappropriatelink.
Ifweapplythemasterimagetothe:hoverstatewithoutadditionalvalues,wemakeonlythetopleftcornervisible—notwhatwewant,thoughclippedbythelinkarea,whichiswhatwewant.Weneedtomovethepositionoftheimagesomehow.
We’redealingwithknownpixelvalues;alittlebitofmathshouldenableustooffsetthatbackgroundimageenoughbothverticallyandhorizontallysothatonlythepiececontainingtheafterstateshows.
That’sexactlywhatwe’lldo:
  1. #panel1ba:hover{background:transparenturl(test-3.jpg)0-200pxno-repeat;}#panel2ba:hover{background:transparenturl(test-3.jpg)-96px-200pxno-repeat;}#panel3ba:hover{background:transparenturl(test-3.jpg)-172px-200pxno-repeat;}#panel4ba:hover{background:transparenturl(test-3.jpg)-283px-200pxno-repeat;}
复制代码
Wheredidwegetthosepixelvalues?Let’sbreakitdown:thefirstvalueisofcoursethehorizontaloffset(fromtheleftedge),andthesecondisthevertical.
Eachverticalvalueisequal;sincethemasterimageis400pixelshighandtheafterstatessitinthebottomhalf,we’vesimplydividedtheheight.Shiftingthewholebackgroundimageupby200pxrequiresustoapplythevalueasanegativenumber.Thinkofthetopedgeofthelinkasthestartingpoint,or0.Topositionthebackgroundimage200pixelsabovethispoint,itmakessensetomovethestartingpoint-200px.
Likewise,iftheleftedgeofeachlinkiseffectively0,we’llneedtooffsetthebackgroundimagehorizontallybythewidthofall<li>spriortotheonewe’reworkingwith.Sothefirstlinkdoesn’trequireanoffset,sincetherearenopixelsbeforeitshorizontalstartingpoint.Thesecondlinkrequiresanoffsetthewidthofthefirst,thethirdlinkrequiresanoffsetofthecombinedwidthofthefirsttwolinks,andthelastrequiresanoffsetofthecombinedwidthofallthreepreviouslinks.
It’sabitcumbersometoexplaintheprocess,butplayingaroundwiththevalueswillquicklyshowyouhowtheoffsetswork,andonceyou’refamiliarit’snotallthathardtodo.
Sothereyouhaveit.Single-imageCSSrollovers,degradabletoasimpleunorderedlist.
Buttons

There’snoreasonwhywehavetoleavethelinkstouchingeachother,side-by-sideastheywereinthepreviousexample.Imagemapsmaybeconvenientinsomespots,butwhataboutseparatingeachlinkintoitsownstand-alonebutton?Thatwaywecanaddbordersandmargins,lettheunderlyingbackgroundshowthrough,andgenerallytreatthemasseparatelyasweneedto.
Infact,thebuildingblocksarealreadyinplace.Wereallydon’tneedtomodifyourcodetooradically;themainchangeisincreatinganewbackgroundimagethatdoesn’tcontinuefromlinktolinklikethelastexampledid.Sincewecan’trelyonthe<ul>forplacingtheoriginalbackgroundimage,we’llendupapplyingittoall<li>sinsteadandoffsettingeachthesamewayweoffsettheafterstatesinthepriorexample.
Withanappropriateimageandabitofspacingbetweeneach<li>,we’vegotbuttons.
Notethatinthisexamplewe’veadded1pxborderswhich,ofcourse,counttowardthefinalwidthofthelinks.Thisaffectsouroffsetvalues;we’vecompensatedbyadding2pxtotheoffsetswhereappropriate.
Irregularshapes

Uptillnowwe’vefocusedonlyonrectangular,non-overlappingshapes.WhataboutthemorecompleximagemapsthatimageslicerslikeFireworksandImageReadyexportsoeasily?Relax,we’vegotyoucoveredtheretoo.
We’llstartthesamewayasthefirstexample,byapplyingthebackgroundimagetothe<ul>andturningofflistitembulletsandsettingwidthsandsoforth.Thebigdifferenceiswherewepositionthe<li>s;thegoalistosurroundeachgraphicalelementwithaboxthattightlyhugstheedges.
Again,becauseoftheabilitytouseabsolutepositioningrelativetothetopleftcornerofthe<ul>,we’reabletopreciselyplaceourlinksexactlywherewewantthem.Nowallthat’sleftistosetupthehoverstates.
Worthnotingisthatinthiscase,asinglesetofbeforeandafterimageswasn’tenough.Becauseoftheoverlappingobjects,relyingononlyoneafterstatewouldshowpiecesofsurroundingobjects’afterstates.Infact,itwouldshowpreciselythepiecesthatfallwithinthelink’sborders.(Easiesttojustseeitinaction.)
Howtoavoidthis?Byaddingasecondafterstate,andcarefullyselectingwhichobjectsgowhere.Themasterimageinthiscasehassplitthepurpleandblueobjectsintothefirstafterstate,andthegreen,orangeandyellowobjectsintothesecond.Thisorderallowsboxestobedrawnaroundeachobject’safterstatewithoutincludingpiecesofthesurroundingobjects.Andtheillusioniscomplete.
Benefitsandpitfalls

Acoupleoffinalthoughts.OurnewCSSSpritemethodtestswellinmostmodernbrowsers.ThenotableexceptionisOpera6,whichdoesn’tapplyabackgroundimageonlinkhoverstates.Why,we’renotsure,butitmeansthatourhoversdon’twork.Thelinksstilldo,andifthey’vebeenlabeledproperly,thenetresultwillbeastatic,butusableimagemapinOpera6.We’rewillingtolivewiththat,especiallynowthatOpera7hasbeenaroundforawhile.
TheotherconcernisfamiliartoanyonewhohasspenttimewithFIR.IntherarecasesinwhichusershaveturnedoffimagesintheirbrowsersbutretainedCSS,abigemptyholewillappearinthepagewhereweexpectourimagestobeplaced.Thelinksarestillthereandclickable,butnothingvisuallyappears.Atpresstime,therewasnoknownwayaroundthis.
Thenthere’sfilesize.Thenaturaltendencyistoassumethatafulldouble-sizedimagemustbeheavierthanasimilarsetofslicedimages,sincetheoverallimageareawillusuallybelarger.Allimageformatshaveacertainamountofoverheadthough(whichiswhya1pxby1pxwhiteGIFsavestoaround50bytes),andthemoreslicesyouhave,themorequicklythatoverheadaddsup.Plus,onemasterimagerequiresonlyasinglecolortablewhenusingaGIF,buteachslicewouldneeditsown.PreliminarytestssuggestthatallthisindicatessmallertotalfilesizesforCSSSprites,orattheveryleastnotappreciablylargersizes.
Andlastly,let’snotforgetthatourmarkupisniceandclean,withalltheadvantagesthatgoalongwiththat.HTMLlistsdegradewonderfully,andaproperimagereplacementtechniquewillleavethetextlinksaccessibletoscreenreaders.Replacingthespriteimageryisdeadsimple,sinceallofourdimensionsandoffsetsarecontrolledinasingleCSSfile,andallofourimagerysitsinasingleimage.
原文毗连:http://www.alistapart.com/articles/sprites/

一般来说还需要用Photoshop或FireWorks(以下简称PS或FW)等图片处理软件将需要制作的界面布局简单的构画出来。
海妖 该用户已被删除
沙发
发表于 2015-1-18 05:31:56 来自手机 | 只看该作者
只要我们努力,无论是怎样的艰难险阻,成功依然会迎面直击。在刚开始时我觉得dreamweavermxXX很难理解。
第二个灵魂 该用户已被删除
板凳
发表于 2015-1-25 21:31:48 来自手机 | 只看该作者
Dreamweaver在所见即所得添加链接时,可以在选中文字后在属性栏中的链接栏中直接输入文件的地址即可。
再现理想 该用户已被删除
地板
发表于 2015-2-4 07:16:19 | 只看该作者
还是在Dreamweaver所见即所得添加链接是,可以选中文字或图片然后按下shift键不放鼠标拖出箭头直接指向文件即可。这是比较简单的也是常用的方之一。
飘飘悠悠 该用户已被删除
5#
发表于 2015-2-9 18:46:42 | 只看该作者
滚动条)层属性--溢出(visible/hidden/scroll/auto)
愤怒的大鸟 该用户已被删除
6#
发表于 2015-2-27 18:32:16 | 只看该作者
还可以在Dreamweaver常用工具中选择超级链接,完成相应的填写即可。
7#
发表于 2015-3-9 12:38:23 | 只看该作者
技术的学习如同长跑。只要越过极限,就会越跑越轻松。技术的学习其实并不像想象中那么可怕,任何技术都并不高深莫测。
兰色精灵 该用户已被删除
8#
发表于 2015-3-17 00:08:18 | 只看该作者
不管老师做怎样的解释,而我却对它感到很是吃力,诸如里面有许多不知道的功能。
谁可相欹 该用户已被删除
9#
发表于 2015-3-23 09:24:39 | 只看该作者
还是在Dreamweaver所见即所得添加链接是,可以选中文字或图片然后按下shift键不放鼠标拖出箭头直接指向文件即可。这是比较简单的也是常用的方之一。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-3 12:42

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表