手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Using the TextRange Object
Using the TextRange Object
摘要:MostuserswillonlywanttousetheinnerText/innerHTMLandouterText/outerHTML...

MostuserswillonlywanttousetheinnerText/innerHTMLandouterText/outerHTMLpropertiesandmethodsdiscussedpreviously.However,thereissomemoreadvancedtextmanipulationthatcanbedoneusinga"textrange"object.TheTextRangeobjectcanbeusedto: Locatethetextforagivenelementoragivenpoint.

Searchforwordsandcharactersinthetextofthedocument.

Movethroughthetextinlogicalunits.

Provideread/writeaccesstotheplaintextandtheHTMLTextinthedocument.

Thisfeaturemightnotbeavailableonnon-MicrosoftWin32platforms.ForthelatestinformationonMicrosoftInternetExplorercross-platformcompatibility,seearticleQ172976intheMicrosoftKnowledgeBase.

Thisarticleconsistsofthefollowingtopics:

OverviewoftheTextRangeObject

WhatDoIDowithaTextRangeObject?

PositioningtheTextRangeObject

CreatingaTextRangeObject

GettingtheContentofaTextRange

ComparingRanges

Commands

OverviewoftheTextRangeObject

TextrangeobjectsareanadvancedfeatureofDynamicHTML(DHTML)thatyoucanusetocarryoutusefultasksrelatedtodynamiccontent,suchassearchingforandselectingtext.Textrangesletyouselectivelypickoutcharacters,words,andsentencesfromadocument.TheTextRangeobjectisanabstractobjectthatcreatesastartandendpositionoverthestreamoftextthatwouldappearintheHTMLdocument.ConsiderthefollowingsimpleHTMLdocument:

<HTML>

<BODY>

<H1>Welcome</H1>

<CENTER><H2>Overview<H2></CENTER>

<P>Besureto<B>Refresh</B>thispage.</P>

</BODY>

</HTML>

Inthisdocument,creatingatextrangeoverthebodyelementwouldpositionthestartatthebeginningofthetextualcontentofthebody,andtheendattheendofthetextualcontentofthebody.Thistextrangewouldcontaintheplaintext"WelcomeOverviewBeSuretoRefreshthispage."

WhatDoIDowithaTextRangeObject?

TherearetwopartstomanipulatingtextwithaTextRangeobject.Thefirstistocreateatextrangesothatthestartandendpositionsencompassthedesiredtext.Thenextstepistoapplyamethodtothetextrange,ormakeacopyofthetexttobeusedelsewhereinthedocument.Oncethetextrangeispositioned,youcansearchfortext,selectthetext,andmakeacopyofthetextanduseitelsewhereinyourdocument.

SeetheTextRangeobjectintheObjectModelReferenceforthepropertiesandmethodssupported.

PositioningtheTextRangeObject

EachtextrangehasastartandanendpositiondefiningthescopeofthetextthatisencompassedbytheTextRangeobject.Whenyoucreateanewtextrange,thestartandendpositionsencompasstheentirecontentbydefault.Usemethodssuchasmove,moveStart,andmoveEndtochangethescopeofthetextrange.

OthermethodscanpositiontheTextRangeobjectwithrespecttoaparticularelement,orapointonthepage.Forexample,moveToElementTextpositionsthetextrangesothatitencompassesthetextcontainedbythegivenelement.ThemoveToPointmethodpositionsthetextrangeatagivenpointwheretheuserclickedamousebutton.Thexandypositionsoftheuser'sclickareknownbythewindow.eventobjectandcanbeusedtopositiontherangeoveragivenpoint.Fromthiscollapsedpoint,therangecanthenbeexpandedtoencompassaword,sentence,orawholetextEdit(theentirepossibleTextRangeobject).

ShowExample

<HTML><HEAD>

<TITLE>moveToPointExample</TITLE>

<script>

functionselectMe(){

varr=document.body.createTextRange();

r.moveToPoint(window.event.x,window.event.y);

r.expand("word");

r.select();

}

</script>

</HEAD>

<BODY>

<H1id=myH1onclick=selectMe()>Clickonawordanditwillhighlight</H1>

</BODY></HTML>

ShowMe

CreatingaTextRangeObject

YoucreateaTextRangeobjectbyapplyingthecreateTextRangemethodtoabody,textArea,orbuttonelement.Youcanalsocreateatextrangefromaselectionmadebytheuser.ThecreateRangemethodontheselectionobjectreturnsatextrange.YoucanusethesamemethodsandpropertiesonthisrangeasyoudoforrangescreatedusingcreateTextRange.

CreatingaTextRangeobjectonthebodywillnotincludethecontentinsideatextAreaorbutton.Conversely,youcannotchangethestartorendpositionofatextrangeoverthetextAreaorbuttontomoveoutsidethescopeoftheseparticularelements.Usethepropertiesprovidedoneachelement,isTextEditandparentTextEdit,towalkthehierarchy.IfthedocumentabovecontainedatextArea,acreateTextRangeonthebodyobjectwouldnotfindthepositionwheretheuseractuallyclicked.Thefollowingreworkstheaboveexampletohandlethiscase.

HideExample

<HTML><HEAD>

<TITLE>moveToPointExample</TITLE>

<scriptfor=documentevent=onclick>

varr

if(window.event.srcElement.isTextEdit)

{

r=window.event.srcElement.createTextRange();

}else{

varel=window.event.srcElement.parentTextEdit;

r=el.createTextRange();

}

r.moveToPoint(window.event.x,window.event.y);

r.expand("word");

r.select();

</script>

</HEAD>

<BODY>

<H1id=myH1>Clickonawordanditwillhighlight</H1>

<TEXTAREA>

There'stextinthiselementtoothatyoucouldclickon

</TEXTAREA>

</BODY></HTML>

ShowMe

GettingtheContentofaTextRange

ThecontentofaTextRangeobjectcanbeviewedwiththetextorhtmlTextpropertyontheTextRangeobject.Thetextpropertyisaread/writepropertythatissimilartotheinnerTextpropertiesontheelementobjects,onlythisreplacesthetextencompassedbyaTextRangeobject.

ThehtmlTextpropertyisaread-onlypropertythatletsyouexaminetheHTMLthatiscontainedwithinthestartandendpointsoftheTextRangeobject.ToaddrichHTMLcontenttothetextrange,usethepasteHTMLmethod.AlthoughyoucanpasteanyHTMLtextthatyouwantintoatextrange,thepasteHTMLmethoddoesnotpreservethehierarchyofthedocument,asdotheinnerHTMLandouterHTMLproperties.AlthoughpasteHTMLwon'tfailifyoupasteinvalidorinappropriatetagsintotherange,theresultingdocumentmightnotlookorbehavethewayyouexpect.IfyoupasteanHTMLfragment,thefragmentisautomaticallyclosedtopreventitfromaffectingsubsequenttextandelements.Forexample,thismeansthatifyourscriptsrelyonordinalpositionsinthedocument'sallcollection,afterapasteHTML,thesourceIndexintothedocument.allcollectionmightpointtoadifferentelement.

ComparingRanges

Youcancreatemorethanonetextrangeatatime,usingthemforindependent,simultaneousaccesstodifferentportionsofthetextinanelement.Youcanalsocopyatextrangebyusingtheduplicatemethod.Thisisusefulifyouwanttemporaryaccesstoaportionoftheoriginalrangebutdon'twanttobotherre-creatingorrestoringtheoriginalrange.YoucandeterminetherelationshipofonetextrangetoanotherbyusingmethodssuchasisEqualandinRange.

Becausetheobjectmodelneverholdsontoatextrange,you'llneedtore-createanyrangewhenevercontrolleavesandthenreentersyourcode.Forexample,anytextrangeobjectscreatedbyaneventhandlerarediscardedwhentheeventhandlerreturns.

YoucandeterminewhetheronerangeisentirelycontainedwithinanothertextrangebyusingtheinRangemethod.YoucandeterminewhethertwotextrangesareidenticalbyusingtheisEqualmethod.Textrangesareidenticaliftheystartandendatexactlythesamepositions.Notethatidenticaltextrangesarealwaysconsideredtobewithinoneanother,meaningtheinRangemethodreturnstrueforthese.

YoucansetthestartorendpointofarangetomatchthestartorendpointofanotherrangebyusingthesetEndPointmethod.Themethodtakestwoparameters:astringdescribingwhichendpointstotransfer,andarangefromwhichthesourceendpointistaken.Thefollowingexamplesetstheendoftheranger1tothestartofr2.

r1.setEndPoint("StartToEnd",r2)

YoucanalsouseStartToStart,EndToStart,andEndToEndtosettheendpoints.

YoucancomparethestartorendpointsoftworangesbyusingthecompareEndPointsmethod.Thismethodcomparestheendpointsandreturns-1,0,or1,indicatingwhethertheendpointofthefirstrangeislessthan,equalto,orgreaterthanthatofthesecond.

Abookmarkisaneasywaytosavethecurrentstartandendpositionsofatextrangeandquicklyrestorethesepositionswhenyouneedthem.YoucreateabookmarkforagivenrangebyusingthegetBookmarkmethod,whichreturnsanopaquestringthatuniquelyidentifiesthebookmark.(Opaquemeansthestringcannotbeexaminedormodified.)YouusethestringwiththemoveToBookmarkmethodtomovethetextrangebacktothesamestartandendpositionsaswhenthebookmarkwascreated.

Commands

Youcanusecommandstoapplyformattingandtocarryoutspecialactionsonthetextofatextrange.YouexecuteacommandbyusingtheexecCommandmethod.Yousupplyacommandidentifierandprovideanyadditionalcommandparameters.Forexample,youcanchangetexttoboldbyusingtheBoldcommandasinthefollowingMicrosoftJScript(compatiblewithECMA262languagespecification)example:

varrng=document.body.createTextRange();

rng.collapse();

rng.expand("sentence");

rng.execCommand("Bold");

ShowMe

Theaboveexamplemakesboldalltextuptothefirstperiodinthedocument.

Notallcommandsareavailableatalltimes.YoucandeterminewhetheracommandisavailableforagiventextrangebyusingthequeryCommandEnabledandqueryCommandSupportedmethods.Foralistofcommands,seeCommandIdentifiers.

Todeterminewhetheragivencommandhasalreadybeenappliedtoatextrange,usethequeryCommandStatemethodtoretrievethestateofthecommand.Thestateistrueifthecommandhasbeenapplied.

【Using the TextRange Object】相关文章:

Javascript中的getUTCHours()方法使用详解

JavaScript的Backbone.js框架的一些使用建议整理

Jquery跨浏览器文本复制插件Zero Clipboard的使用方法

onpropertypchange

javascript检测两个数组是否相似

接收键盘指令的脚本

基于zepto的移动端轻量级日期插件--date

理解Javascript图片预加载

初步使用bootstrap快速创建页面

js控制excel打印完美解决方案

精品推荐
分类导航