逸逸记事
逸逸记事

我的分类(专题)

首页(175)
儿子(9)
SIP技术(9)
Web2.0(12)
摄影和DVD(8)
软件开发随笔(18)
名古屋打工生活(11)
微软技术开发(47)
Java技术(12)
加拿大移民生活(20)
生活点滴(6)
第一份工作--上海贝尔(18)
完成项目(13)
回国后的生活(0)


最新日志
独行者
终于知道什么叫外包了
人生悲哀之事
水晶报表中显示动态图片
水晶报表中的简单参数设置
怀念下小黑
dotnet中的数据连接Timeout
老板的思路
又买房了
交通事故

最新回复
回复:独行者
回复:怀念下小黑
回复:老板的思路
回复:mjSip学习笔记
回复:老板的思路
回复:dotnet中的数据连接Timeo
回复:mjSip学习笔记
回复:交通事故
回复:交通事故
回复:又买房了

留言板

签写新留言

您好,很希望问您一个关于jain-sip
生活经历就是最大的财富,羡哦~
java的Web开发问题
回复:疑问
IT还不如妓女呢,呵呵
myjavaserver的空间
求助
您的子域名已开通

统计
blog名称:人在旅途
日志总数:175
评论数量:505
留言数量:13
访问次数:1674040
建立时间:2005年12月7日

链接

 

生命是过客,人在旅途。奶奶是信基督教的,没啥文化,却养育了四子二女,还带过九个孙辈。老人家对生命的看法就是“人都是客人,迟早要回去的。”就以《人在旅途》来纪念她。

 

«October 2025»
1234
567891011
12131415161718
19202122232425
262728293031

公告
  本人上传的源程序中可能引用或使用了第三方的库或程序,也可能是修改了第三方的例程甚至是源程序.所以本人上传的源程序禁止在以单纯学习为目的的任何以外场合使用,不然如果引起任何版权问题,本人不负任何责任.




     本站首页    管理页面    写新日志    退出
调整中...
[软件开发随笔]PopupMenu in HTML
人在旅途 发表于 2006/1/23 8:46:45

The result: Use the <Div> Tag and it's style.display to show and hide it. So we can make menu.Sample: /***************************************************/ <HTML><HEAD><TITLE>AN ALERT EXAMPLE</TITLE> </HEAD><BODY><FORM><CENTER><H1>CLICK THE BUTTON...</H1><BR><INPUT  TYPE=BUTTON VALUE="ALERT!" onClick="Alterter()"><DIV ID="idMenu2">            <A HREF="COM'>http://www.microsoft.com/workshop/server/asp/comtutorial.asp">COM Objects in ASP Tutorial</a> <BR>            <A HREF="ActiveX'>http://www.microsoft.com/sitebuilder/features/aspactx.asp">ActiveX Components w/ASP</a> <BR>            <A HREF="Tuning'>http://www.microsoft.com/isn/techcenter/tuningIIS.htm">Tuning IIS Performance <IMG SRC="leave-site.gif" WIDTH="17" HEIGHT="11" BORDER="0" ALT="Non-SBN link"></a> <BR>            <A HREF="Debugging'>http://www.microsoft.com/workshop/server/asp/debug.asp">Debugging with IIS</a> <BR>            <A HREF="15'>http://www.microsoft.com/sitebuilder/archive/features/ASPtips.htm">15 ASP Tips</a> <br>            <A HREF="Components'>http://www.microsoft.com/workshop/server/asp/aspvs97.asp">Components with VS 97</a> <br>            <A HREF="In-line'>http://www.microsoft.com/workshop/server/asp/inline.asp">In-line HTML Editor</a> <br>            <A HREF="Components'>http://www.microsoft.com/workshop/server/asp/comp.asp">Components with ATL</a> <br>            <A HREF="ASP'>http://www.microsoft.com/workshop/server/asp/active.asp">ASP Session Management</a> <br>         </DIV> <SCRIPT LANGUAGE = JavaScript> idMenu2.style.display = "none"</SCRIPT></CENTER></FORM></BODY><SCRIPT LANGUAGE = JavaScript> function Alterter()  {    idMenu2.style.display = ""  setTimeout("Alterter2()",2000)   } function Alterter2()  {  alert('213')   } </SCRIPT></BODY></HTML> /************************************************/ More:   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnhtmau/html/beghtml.asp?frame=true 1.    MSDN Home >  MSDN Library >  HTML and Dynamic HTML >   Rate this page:  26 users             2.2 out of 5 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndhtml/html/popupmenu.asp  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndhtml/html/dhtmlpopup.asp Build a Pop-up Menu Using Dynamic HTML and JavaScript: Part I   Robert Carter George Young, Web Design Engineer Microsoft Corporation January 23, 1998 DownloadDownload the sample Dynamic HTML Pop-up Menu code (69 KB). Contents Introduction Functional Description The Code Adapting the Pop-up Menu Code to Your Site Summary Introduction A key navigational element of the MSDN Online Server area design is a pop-up menu written by George Young. It uses Dynamic HTML and JavaScript to reveal site-wide navigation to Server area visitors from every page, saving them time and effort in their search for useful information. Of the ten different sections available in the Server area, seven use the pop-up menus to display the list of articles for that section. (The other three sections point to one document apiece, and don't need the pop-up menu function.) At present, the pop-up menu is visible only to surfers using Microsoft® Internet Explorer 4.0 on the Windows 95® or Windows NT® platforms. People using other browsers or platforms are sent to a standard table-of-contents page, and can jump from there to specific articles of interest. This article describes how our pop-up menus work, and provides all the code and discusses considerations necessary to adapt it to your site. Functional Description If you have Internet Explorer 4.0 on Windows 95 or Windows NT, skip over to the Server area home page and click any navigation item (except the Table of Contents, Editor's View, and Relevant Links items) along the left side of the screen. An additional menu box listing the contents of that section appears immediately to the right of the navigational item you selected (and has a nice scroll-down effect). If you move the mouse over one of the article titles in the menu, the title changes color. Clicking the title sends you to the article. The menu remains visible until you click somewhere else on the page. [POP3383B 38327 bytes ] Figure 1. Screen shot demonstrating the pop-up menu The Code So much for the easy stuff. Now I get to tell you how it works. Sniffing to Provide the Right Navigation The Server area navigation menu (the section with the purple background) is a table. Each cell in the table, as you've probably surmised, is a GIF image. To determine whether to load the images that activate the pop-up menu, we use Active Server Pages (ASP) to sniff for the user's browser and platform. If the browser is Internet Explorer 4.0 for Windows 95 or Windows NT, the image tag used includes two attributes, ID and CLASS: <IMG ID="idMenuTitle1" CLASS="clsMenuTitle"  SRC="http://msdn.microsoft.com/workshop/server/graphics/server-nextgen-navb.gif"  WIDTH="140" HEIGHT="27" BORDER=0 ALIGN=TOP ALT="Next Generation"> For other browsers or platforms, the image tag is linked to the selected section of the table-of-contents page: <A HREF="500)this.width=500'>http://msdn.microsoft.com/workshop/server/toc.asp#nextgen"><IMG  SRC="http://msdn.microsoft.com/workshop/server/graphics/server-nextgen-navb.gif"  WIDTH="140" HEIGHT="27" BORDER=0  ALT="Next Generation"></a> This provides graceful navigation for everyone who visits the site. The traditional-style annotated table-of-contents page is accessible to all users by clicking the Table of Contents item. Activating the Menu Now we'll concentrate on the pop-up menu functionality. The ID="idMenuTitle1" attribute is accessed by a script through an onclick() event-handler in the <BODY> tag of the page: <BODY TOPMARGIN=0 LEFTMARGIN=0 BGCOLOR="#FFFFFF"  LINK="#000066" VLINK="#666666" TEXT="#000000" ONCLICK="doMenu()"> The onclick() event-handler in the body tag calls the doMenu() function when the user clicks anywhere on the page. Here is doMenu():    var sOpenMenuID = ""   var iTimerID    function doMenu() {      if (bIsIE432) {         var eSrc = window.event.srcElement         window.event.cancelBubble = true         if (sOpenMenuID != "") {            document.all[sOpenMenuID].style.display = "none"         }         if (eSrc.className=="clsMenuTitle") {            var nMenuNum = eSrc.id.substring(eSrc.id.length - 1,eSrc.id.length)            sOpenMenuID = "idMenu" + nMenuNum            var eMenu = document.all[sOpenMenuID]            eMenu.style.clip = "rect(0 0 0 0)"            document.all[sOpenMenuID].style.display = "block"            nChunk = 25            iTimerID = window.setTimeout("showMenu(" + eMenu.id + "),10")         }      }  } First, doMenu() checks to see whether an appropriate version of Internet Explorer is being used (if (bIsIE432)). This Boolean (true/false) variable is set to true in an earlier JScript™ statement if the user's browser is Internet Explorer 4 for Windows 95 or Windows NT. The var eSrc = window.event.srcElement statement assigns the element that was clicked to the variable eSrc (in a variation of the Dvorak notation, we use "e" to stand for element). The window.event.cancelBubble = true statement prevents the command from "bubbling up" (if, like me, you don't really know what that means, I encourage you to read Bubble Power: Event Handling in Internet Explorer 4.0 by Michael Wallent). The if (sOpenMenuID != "") conditional statement checks whether another menu on the page is open. If there is, the open menu is closed with the document.all[sOpenMenuID].style.display = "none" statement. Selecting Which Menu to Display The second half of doMenu(), shown in the previous section, selects and displays the appropriate menu. After prepping the page to display the menu (by closing any open menus), doMenu() tests whether the clicked element belongs to the class clsMenuTitle. In this case it does (because the Next Generation GIF we're clicking contains a CLASS="clsMenuTitle" attribute). Once we verify that a pop-up menu is called, we need to figure out which of the seven menus to display. To do that, we perform a little sleight-of-hand with the Next Generation GIF ID declarations. On MSDN Online Web Workshop, we use naming conventions for all attributes accessible by script. Thus, the GIFs that activate the pop-up menu have a similar ID: idMenuTitle followed by an integer (1 through 7). The variable nMenuNum points to the integer by subtracting the eSrc.id.length-1 from the total eSrc.id.length. The integer is then assigned to nMenuNum using the eSrc.id.substring property:   if (eSrc.className=="clsMenuTitle") {     var nMenuNum = eSrc.id.substring(eSrc.id.length - 1,eSrc.id.length) Once the integer is isolated and assigned to nMenuNum, we use a variable just declared (with a starting value of ""), sOpenMenuID, that concatenates the text string idMenu and nMenuNum to yield a new value of idMenu1. The var eMenu = document.all(sOpenMenuID) statement creates a pointer to the element of the page associated with the variable sOpenMenuID—which now has the value idMenu1. The next two lines assign a style of rectangle to eMenu, and then tells Internet Explorer to show all parts of the document associated with idMenu1 (as of this moment a dimensionless rectangle). The nChunk = 25 statement assigns a starting value to a variable we will use to control the display of the Next Generation menu. Finally, in the next line, a timer is started using the window.setTimeout() method. In this case, we set the timer to wait 10 milliseconds and then call our showMenu() function, which will actually display the menu.. Displaying the Menu Now we can finally display the Next Generation menu. The menu is simply a <DIV> with an ID that matches the one generated from the sOpenMenuID concatenation (and a class of clsMenu). Each menu item is presented within an anchor pointing to the article's URL: <DIV ID="idMenu1" CLASS="clsMenu">  <A HREF="http://msdn.microsoft.com/workshop/server/nextgen/pws.asp">  Web Services for PCs</a> <BR>  <A HREF="http://msdn.microsoft.com/workshop/server/nextgen/nextgen.asp">  International ASP</a> <BR></DIV></TD> George being George, the menu display must be elegant, so the expression in parentheses refers to a function called showMenu(): var nChunkfunction showMenu(eMenu) {  eMenu.style.clip = "rect(0 100% " + nChunk + "% 0)"  nChunk +=25  if (nChunk <= 100) {    iTimerID = window.setTimeout("showMenu(" + eMenu.id + "),10")  }  else {    window.clearTimeout(iTimerID)  }} showMenu() creates a scroll-down effect by displaying the menu in 25% chunks every 10 milliseconds. The first time through, nChunk is set to 25, and showMenu creates a rectangle whose width extends to 100% of its intended size and whose height extends to 25% of its eventual size (the eMenu.style.clip statement). nChunk is then incremented by 25, so the next time showMenu is evaluated (10 milliseconds later), 50% of the menu's eventual height displays. And so on, until nChunk is greater than or equal to 100, at which time the timer variable is cleared, stopping the timer. [POP3383C 7699 bytes ]Figure 2. The CSS hover property in action The style of the pop-up menu is outlined in our style sheet, and the menu-item color-change happens by virtue of the hover property. For more on CSS properties and how to apply them to your HTML documents, see Cascading Style Sheets in Internet Explorer 4.0. .clsMenuTitle { cursor:hand; }.clsMenu {   border:solid 1; border-color:khaki olive olive khaki;   background-color:darkkhaki; position:absolute; display:none;   padding:1px; width:150px; z-index:1; padding-left:5px;   font-family:verdana; font-size:8pt;   }.clsMenu A { text-decoration:none; color:black; }.clsMenu A:hover { color:olive; } Adapting the Pop-up Menu Code to Your Site Although there's a fair amount of code, adapting it to your site is fairly trivial, especially if you include the script and style sheet on each page through ASP include statements (as we do). The key is to make sure you have all the script, CSS, and inline attributes in place, and keep the properties and values in sync. For each menu (or list of links) you wish to include, create a DIV item just like the one outlined in Displaying the Menu. Make sure to use the same CLASS values that we do for the menu titles (clsMenuTitle) and the menus (clsMenu), and to use the incremental numbering system for the related <DIV>s (idMenu1, idMenuTitle1, and so on). If you have more than nine menus, you'll need to change your script to eSrc.id.length-2 and use two digits in all your IDs (idMenu01, idMenuTitle01, and so on). Download our sample Dynamic HTML code with helpful comments (available at the top of this page) and peruse it to see what CSS, scripts, and inline attributes are placed where. Summary Pop-up menus provide an elegant way to simplify the navigation of complex or data-heavy sites. Users have immediate access to all the articles on a site from a small piece of page real estate. They avoid the annoyance of using the back button repeatedly or scrolling in their quest to find the information they seek, and they spend a lot less time waiting for unnecessary pages to load. You benefit from the reduction in server hits that comes with more efficient use of your site navigation. And the menus looks really good, too. If you want to spend more time learning DHTML, you can start with the following: Michael Wallent authors a monthly column on MSDN Online, the DHTML Dude. MSDN Online offers a range of options as well: Inside Dynamic HTML, the companion Web site to the book, provides many great demos and techniques.  Contact Us   |  E-Mail this Page   |  MSDN Flash Newsletter   © 2002 Microsoft Corporation. All rights reserved.   Terms of Use  Privacy Statement   Accessibility   2.    MSDN Home >  MSDN Library >  HTML and Dynamic HTML >   Rate this page:  15 users             3.4 out of 5  Build a Pop-up Menu Using Dynamic HTML and JavaScript: Part II Robert Carter Technical Writer MSDN Online George Young Web Design Engineer MSDN Online Download Download the pop-up menu files (70 KB). Contents Introduction The Major Issues Raised by Version One All Hail the New Code Summary Introduction Back in January, when the Server area of Workshop launched its redesign, George Young and I wrote about the DHTML pop-up menu he created for it. In July, the Server area was assimilated into the major new redesign of the Web Workshop (whose DHTML drop-down menu was partially inspired by the Server menu). We received a lot of mail about the Server menu, though, and because most of the questions were so good, we thought we'd do our own "Web Men Talking" stint and answer them in a follow-up article. In response to the major questions raised by the first article and code, we (um, George) generated a new version of the pop-up menu that makes customization a lot easier, so much so that your code-challenged narrator can actually write a few paragraphs without having to traipse back to George's office with a list of questions. For this article, we'll rehash the most common questions we received, and discuss the solutions we developed. Bear in mind that, at least to some of us (read: Robert), this stuff is hard (writing about this stuff reminds me of the Gary Larson cartoon where the student asks to be dismissed because his brain is full). George is an elegant coder, and often tries to accomplish multiple objectives within a single statement. It confuses Robert to no end. The Major Issues Raised by Version One The first article and code sample generated questions that fell into three major categories: menu positioning (especially dealing with frames) cross-browser functionality (especially Navigator) cascading functionality (to display second-level menus) We'll treat each of these issues in turn. Menu Positioning We were surprised at the number of questions we got about positioning where the menus pop up. Then we looked at the code and realized we had given no positioning information whatsoever. The default positioning Microsoft Internet Explorer 4.0 and above relied on fit our needs perfectly, scrolling out immediately adjacent to the image that was clicked on.   Figure 1. Pop-up menu with default positioning All well and good for us, but anybody that wanted the menu to open elsewhere had to start from scratch. One of the biggest problems our default positioning created was for those folks that tried to implement the pop-up code in a frameset. The code would function, but the menus themselves would be clipped, as shown below.   Figure 2. Pop-up menu getting clipped by frame border This would occur if you had any windowed element on the page. Java applets, dialog boxes, Microsoft ActiveX controls, and IFRAME elements would all overwrite the pop-up menu. The reason stems from the limitations of the HTML container; no element inside HTML can cross windows. End of story. Because we didn't feel like taking the time to develop an ActiveX control that could cross a frame border, we repositioned the original pop-up menu to expand just to the right of and below the graphic of a particular area. If the pop-up is still clipped, you can shrink its size to fit the space available, or move the pop-up all the way to the left border.   Figure 3. Pop-up menu repositioned and resized to fit within left frame This workaround is clearly more awkward. Is it more intuitive to have the pop-up immediately to the right or below the area in question? If it pops up immediately to the right, the text of the area is blocked; if immediately below (and to the right of the graphic), it's unclear which area is being displayed. Nonetheless, it works. Cross-Browser Functionality Many of you wrote wondering why our pop-up menu works in Internet Explorer 4.0 (and above) but not Netscape Navigator 4.0 and above. The short answer is because the DHTML implementations are not entirely compatible. We use features and functions of Internet Explorer's DHTML implementation that Netscape doesn't recognize. Sorry. The code we provided does handle all browser types, though. All browsers that aren't Internet Explorer 4.0-compatible can still load the menu. The only difference is that when a user clicks on one of the graphics, it functions simply as a hyperlink instead of displaying the pop-up menu. You have two options from here. You can develop a TOC page for each section (in our example, Next Generation, Active Server Pages (ASP), Feature Expert, and so on, would each get their own TOC pages), or one generic TOC page with anchors (for example, a generic TOC page entitled TOC.htm; a redirect to the Next Generation section would use the HREF "TOC.asp#nextgen"). While this menu was running on MSDN Online's server section, we used the latter method. In case cross-browser pop-up menu functionality is a "must-have", we did a quick search of the Web for a couple of examples. Happily, there were a few (we love the Web). The first cross-browser example we found came from one of the best sites out there for learning DHTML, InsideDHTML. The cross-browser example they provide looks similar to one I saw on WebMonkey when the 4.0 browsers first came out. It's snazzy because it opens and closes at the click of a mouse, and thus takes up very little screen real estate when inactive. In addition, a few alert readers pointed out to us that there's been a whole series of articles on a cross-browser pop-up menu implementation over in the DHTML Lab. Their latest version is 3.04. They keep updating it in response to popular demand. Well worth a visit. Our good friends at Netscape have also done some work in this direction. Although this article refers to the code for a collapsible list, it should be relatively easy to adapt to a menu inside a table or a frame. In general, if you want to limit your DHTML functionality to being cross-browser-compatible, we suggest you visit the section of the InsideDHTML site that maintains a cross-browser library. While you might not take advantage of the entire Internet Explorer DHTML implementation, you might avoid having to maintain multiple versions of code, especially if you don't have to support 3.x versions of Internet Explorer or Navigator, or other browsers that currently don't support DHTML. Cascading Menu Functionality Another interesting request from our readers was whether we could add more levels to our menus. As a result, they could embed multiple content areas without requiring users to navigate to another page. The DHTML Lab example we referenced above already includes cascading menu support. The InsideDHTML site has another example, and we show a screenshot of their implementation below:   Figure 4. InsideDHTML cascading menu example And yes, we could do that, but it's not trivial, so we didn't. Instead, because both the InsideDHTML and DHTML Lab folks did our work for us, we'll point you there (say Hi for us). Cross-platform developers beware, though, that the InsideDHTML example only works on Internet Explorer 4.0 and above browsers. All Hail the New Code Now that we've described what we did (and didn't) do with the code, I can describe how each of the features are implemented. Since George has found some coding hobby horses to ride in the meanwhile, the code has gotten simpler for you to implement, and tougher for me to explain. Please bear with me. Modified Browser-Sniff Code We'll start with menu.asp. menu.asp begins with our new server-side sniff code, shown below: function BrowserData(sUA){  var iMSIE = sUA.indexOf("MSIE");  this.userAgent = sUA;  this.browser = (iMSIE > -1) ? "MSIE" : "Other";  this.majorVer = parseInt(sUA.substring(iMSIE + 5, iMSIE + 6));  this.getsMenus = ("MSIE" == this.browser && 4 <= this.majorVer);}var oBD = new BrowserData(newString(Request.ServerVariables("HTTP_USER_AGENT"))); First, we do our sniffing within the BrowserData(sUA) function (where sUA is our modified Hungarian notation for UserAgent string). The first line assigns the variable iMSIE to the index of the user agent string (HTTP_USER_AGENT is part of ASP's ServerVariables collection, which is part of the Request object). Remember , the indexOf method returns an integer indicating the beginning of the specified string; if the indicated substring is not part of the specified string, indexOf returns a value of -1. Just for grins, I checked for my user agent strings for each of my copies of Internet Explorer and Navigator, and got the following: Internet Explorer Mozilla/4.0 (compatible; MSIE 4.01; Windows NT; ITG-IE401SP1) Navigator Mozilla/4.07 [en] (WinNT; I ;Nav) Next we use the "this" statement to refer to the current object (BrowserData) and assign it a bunch of properties: userAgent is assigned the entire user agent string browser is assigned "MSIE" or "Other" depending on whether the user agent string includes the substring "MSIE" majorVer is assigned which major version of Internet Explorer we're dealing with by isolating the substring one space after the "MSIE" string (note that for my Navigator browser this technique will return a value of "l"; to get the major version number for Navigator we'd need to isolate the character nine spaces into its user agent string) getsMenus is assigned True if the comparison test reveals the user is running Internet Explorer version 4.0 or greater. The server-side sniff is used to figure out whether or not to send the pop-up menu-related files to the requesting browser. If so, we send the files down using the Response.Write method. <%  if (oBD.getsMenus)  {    Response.Write('<SCRIPT SRC="/menudemo/popup/menus.js"></SCRIPT> \n');    Response.Write('<LINK REL="stylesheet" TYPE="text/css" HREF="menus.css"> \n');  }%> Put Everything Away Before Opening a New Menu The menus.js file is where all the pop-up menu functionality resides, while menus.css supplies the style sheet information. Within menus.js, the major work is done by the DoMenu function. (By the way, if you find my plodding explanations for menus.js tiresome, skip directly to the menus.js file itself: George has done a bang-up job of adding comments, enough so that I fear being redundant in this article.) The first half of DoMenu appears below. It moves from the general (was a menu clicked?) to the specific (if so, which one?) because some actions we want it to take are global (if a menu was open, close it), and some depend on a particular menu (if the user clicked the same menu that was already open, exit the function). function DoMenu(){  window.event.cancelBubble = true;  var eSrc = window.event.srcElement;  if ("object" == typeof(document.all[sOpenMenuID]))  {    document.all[sOpenMenuID].style.visibility = "hidden";    if (sOpenMenuID == eSrc.id.replace("imgMenuTitle","divMenu"))    {      sOpenMenuID = "";      return false;    }    else    {      sOpenMenuID = "";    }  }  if ("clsMenuTitle" == eSrc.className)  {    window.event.returnValue = false;... The first thing we do is cancel the document onclick event from bubbling up the event hierarchy. Next, we identify what was clicked using the srcElement property, and assign it to the variable eSrc. The first conditional is a bit of sleight of hand that accomplishes the task of closing any menu that might be open. sOpenMenuID is the variable we use to store the ID of any open menu. We originally assign it to be blank. If no menu is open, sOpenMenuID is blank; if a menu is open, sOpenMenuID holds a string representing the ID of the menu. But we can't simply use the visibility property to hide "all" of the items in the document with the sOpenMenuID identifier; if sOpenMenuID is blank, we would get an error. Instead, we wrap that declaration in a conditional so the visibility property only gets set on "real" objects. The conditional test uses the typeof operator, which returns one of six strings corresponding to each type of expression Microsoft JScript can recognize. In this case, the visibility property is set only when document.all[sOpenMenuID] is an object (sOpenMenuID becomes an object reference when it is wrapped in the document.all container). Whew. Please rest awhile—Robert's going to go refill his cup of coffee. Next, now that we know we had a menu open, we ask whether the user clicked the same menu item again. If they did, we reassign sOpenMenuID to be a blank string and exit the function; our work is done. But again fancy-pants Young made things interesting. The comparison test in the conditional was multi-agenda'd. Remember that the pop-up menu is activated from a table populated by a bunch of images. Each image in the table has its own ID. A user that clicks on the "Next Generation" image clicks on an element with an ID value of "imgMenuTitle1". Each menu image has an ID that begins with "imgMenuTitle" and closes with a unique integer. <TD ALIGN="left" VALIGN="top"><A  HREF = "500)this.width=500'>http://www.microsoft.comhttp://msdn.microsoft.com/workshop/server/toc.htm#nextgen&"><IMG   WIDTH="140" HEIGHT="27" BORDER="0" ALIGN="top" ALT="NextGeneration"   ID="imgMenuTitle1" CLASS="clsMenuTitle" SRC="server-nextgen-navb.gif"></A></TD> A menu is associated with each image, and each menu is stored as a unique DIV in the menus.inc include file. Each menu DIV also has an ID, in this case the string "divMenu" followed by an integer. Conveniently (and, yes, by design), the integer for a menu matches the integer for its associated image. The "Next Generation" menu DIV thus looks like the following: <DIV ID="divMenu1" CLASS="clsMenu"><A  HREF = "Web'>http://www.microsoft.com/nextgen/pws.asp">Web Services for PCs</A><BR><A  HREF = "International'>http://www.microsoft.com/nextgen/nextgen.asp">International ASP</A><BR></DIV> To recap, the user has clicked on a menu image which has an ID "imgMenuTitle" plus an integer. What we want to know is whether the image that was just clicked corresponds to the menu that was last opened (that is, if the "Next Generation" menu was last opened, did the user click on the "Next Generation" image again?). Since we know that the numbers for the menu images and DIVs are identical, if we could just switch out the "imgMenuTitle" string and substitute "divMenu" instead, we're golden. George implemented both the comparison and the switch-out in one fell swoop, avoiding the need for creating a temporary variable and then performing some string manipulations on it, by using the replace method on the element's id property. if (sOpenMenuID == eSrc.id.replace("imgMenuTitle","divMenu")) If it turns out that the menu image just clicked was for the same menu that was just open, we reset sOpenMenuID to a blank string and exit the function. If the menu image clicked was different, we simply reset sOpenMenuID to a blank string (if we need to, we'll re-establish its value later; since everything hinges on sOpenMenuID, we want to make sure we don't inadvertently store a value there that screws up the menu functionality later). So many words, so little code... Positioning and Rendering the Menu Now that any menus that were already open have been closed, and the menu image that was clicked on needs to be opened, we can talk about the rest of DoMenu: (DoMenu cont'd) if ("clsMenuTitle" == eSrc.className){  window.event.returnValue = false;  sOpenMenuID = eSrc.id.replace("imgMenuTitle","divMenu");  if ("object" == typeof(document.all[sOpenMenuID]))  {    var eMenu = document.all[sOpenMenuID];    iChunk = iChunkStep;    var eTR = eSrc.parentElement.parentElement.parentElement;    var eTABLE = eTR.parentElement.parentElement;    if ("right" == sMenuPos)    {      eMenu.style.left = eTABLE.offsetLeft + eSrc.width;      eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop;    }    else    {      eMenu.style.left = eTABLE.offsetLeft + 26;      eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop + eSrc.height;    }    eMenu.style.clip = "rect(0 0 0 0)";    eMenu.style.visibility = "visible";    return window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);  }} We start with a double-check--are we sure a menu image was clicked (developers are so paranoid!)--by testing to make sure the class name of the clicked object matches the class name of the menu images, "clsMenuTitle." If yes, the first thing we do is cancel the default event associated with the image (an HREF that would send the user to that section's TOC page). In effect, we're saying "No, no, no, stay right there; because you use such a wonderful browser, we'll bring the menu to you." We then reassign the menu DIV ID to sOpenMenuID (I'm not going into how again), and (for crying out loud) introduce the same type of conditional we discussed before. So if we're really dealing with a menu image, we're gonna start some menu-drawing real soon now. After we declare eMenu as an object reference to the menu object (again, by wrapping it in the document.all object), we're going to get our bearings on the rendered page, which we'll do by figuring out the location of the row in the table, and the table on the page. To figure out which row we're in, we assign eTR to the great-grandparent element of eSrc (the element that was clicked). (If you look at the code of each reference, we have an image <IMG> inside an anchor <A> inside a table cell <TD>, which is, finally, inside great-grandma <TR>. I've reproduced it below and higlighted the parentage elements). <TR><TD ALIGN="left" VALIGN="top">  <A  HREF = "500)this.width=500'>http://www.microsoft.comhttp://msdn.microsoft.com/workshop/server/toc.htm#nextgen"><IMG  WIDTH="140" HEIGHT="27" BORDER="0" ALIGN="top" ALT="Next Generation"   ID="imgMenuTitle1" CLASS="clsMenuTitle" SRC="server-nextgen-navb.gif"></A></TD></TR> Next, we take the grandfather of the TR tag to position the TABLE on the page. Why not the parent element, you ask? Well, because the parent of the table row tag is actually the TBODY tag, which is implicit when you create a table, whether you actually use it or not. Even so, we thought that the position of TBODY, if not declared, would default to the position of the TABLE tag, rendering our oversight a distinction without a difference. Wrong again. Rather than spin our wheels for a while longer trying to figure out why, we punted and used the grandparent element. So should you. Now that we have our two positioning keys (the TR and TABLE locations), we can use them to draw our menus. And we've given you lots of choices about the display, both location and the display animation itself, which are set by assigning string values to two variables, sMenuPos and sMenuStyle. sMenuPos refers to where the pop-up menu will be drawn relative to the clicked menu graphic: selecting "right" causes the pop-up to be drawn adjacent to the table at the same height as the clicked image (see Figure 1); "below" (or anything else, really) causes the pop-up to be drawn immediately below the image selected, and immediately to the right of the graphic (so any images below aren't obscured, as is shown in Figure 3). if ("right" == sMenuPos){  eMenu.style.left = eTABLE.offsetLeft + eSrc.width;  eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop;}else{  eMenu.style.left = 36;  eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop + eSrc.height;} For the "right" positioning style, we add the eTABLE left offset to the width of the image to set the, for lack of a better term, "x" coordinate; adding the eTABLE top offset to the eTR top offset gives us our "y" coordinate. Otherwise, we use a fixed positioning of 36 pixels for "x" and add the eTABLE and eTR top offsets to the height of the eSrc element for "y." Given our "x" - "y" starting point, we now start drawing the rectangle that will hold the menu: eMenu.style.clip = "rect(0 0 0 0)";eMenu.style.visibility = "visible";return window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay); We initialize the menu rectangle with clip of zero dimension, make it visible, and initiate our display, which we'll control and effectively animate with the setTimeout method. setTimeout calls the function ShowMenu, and the iChunkDelay variable is assigned initially to 10, which means we'll evaluate ShowMenu() in 10 milliseconds. ShowMenu(eMenu) calls yet another function, GetShowStyle(), and continues to invoke the setTimeout method until iChunk exceeds 100; iChunk is incremented by iChunkStep with each pass through ShowMenu()(the larger the value of iChunkStep, the fewer cycles through ShowMenu(eMenu)). function ShowMenu(eMenu){  eMenu.style.clip = GetShowStyle();  if (100 >= iChunk)  {    window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);  }  iChunk += iChunkStep;} GetShowStyle() has three display options, effectively equating to the type of "pan" you want to simulate: "down", "across", and "diagonal." As you can see from the code snippet below, the different settings of sMenuStyle control which dimension is unfurled in the display animation ("down", for example, sets the top at 0, right at the menu's full width (100%), bottom in iChunk percentage increments, and left at 0). function GetShowStyle(){  if ("down" == sMenuStyle) return "rect(0 100% " + iChunk + "% 0)";  else if ("across" == sMenuStyle) return "rect(0 " + iChunk + "% 100% 0)";  else if ("diagonal" == sMenuStyle) return "rect(0 " + iChunk + "% " + iChunk + "% 0)";  else return "rect(0 100% " + iChunk + "% 0)"; } We encourage you to play with all the effects, especially the settings of iChunk, iChunkStep, and iChunkDelay, to see how they affect the menu animation. Finally, if you want to control the colors of the drop-down box, its width, or other parameters, you can mess with the menus.css file. Summary So much for a short, succinct update of the original Pop-up Menu article! Jeez. We've covered a lot of programming concepts in our descriptions of the code, from ASP server objects to Jscript-type operators to DHTML methods. As a result, I've droned on longer than I might otherwise care to, and the term "feature bloat" has some resonance for me. Good code can be dense, though. There are many instances in our pop-up menu where George killed a few birds with a single line of code, and Robert was left to meander around and attempt a cohesive narrative. It feels like giving driving directions to my house; it seems more complicated to give the directions than drive the car, especially the critical little turns that are so easy to miss. All the same, thanks for bearing with us. Hopefully this time around we've given you all the tools, and the knowledge, you need to implement our pop-up menu on your site.

阅读全文(4235) | 回复(0) | 编辑 | 精华


发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)

站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 1.012 second(s), page refreshed 144810603 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号