Web-based UI components-tree menu (2)

Source: Internet
Author: User

Starting from this article, you need to have some Javascript and DOM-related knowledge to continue learning smoothly. Since Javascript and DOM are not something that can be done in just a few words, if you are not familiar with them, Please study them here and continue: Javascript online tutorial (English) DOM online tutorial (English ). GetElementsByClassName ()

To find out the tree menu from a lot of HTML code (maybe there are multiple), let's first implementclassNameHow to find a DOM node:getElementsByClassName. This is a simple but practical extension of the browser's own DOM method.

This method has two parameters:eleSpecify which DOM node is used as the root node (that is, onlyele),classNameSpecifies the class attribute of a qualified node.className. Its return value is an array that stores all nodes that meet the conditions.

Function getElementsByClassName (ele, className) {// obtain all subnodes if (document. all) {var children = ele. all;} else {var children = ele. getElementsByTagName ('*');} // traverse the subnode and check the className attribute var elements = new Array (); for (var I = 0; I <children. length; I ++) {var child = children [I]; var classNames = child. className. split (''); for (var j = 0; j <classNames. length; j ++) {if (classNames [j] = className) {elements [elements. length] = child; break; }}return elements ;}

The first if-else language is to be compatible with IE5 (IE5 cannot rundocument.getElementsByTagName('*')). Note that do not use the browser detection method to write scripts. Instead, you should directly use the statements to test whether execution can be performed. If the returned value isnullOrundefined, Then use another method. Such scripts can have better compatibility and robustness.

  elements[elements.length] = child;The array is not used for compatibility with IE5.pushMethod. If you must usepushMethod, You can executegetElementsByClassName()Previously, reload 1PushMethod. The Code is as follows:

Array.prototype.push = function(value){ this[this.length] = value;}

Note: I originally hopedgetElementsByClassNameCan also be likepushWrite the same method, suchHTMLElement.prototype.getElementsByClassName = .... However, during actual operationsHTMLElementThis object is not fixed, and each tag seems to be different. If you have a solution, please let me know. Thank you.

Now we can easily find all the tree menus on the page:

Var trees = getElementsByClassName (document, 'treeview'); for (var I = 0; I <trees. length; I ++) {alert ('I am the tede' + I + 'tree menus'); // You can process each tree menu in more detail here}

Finally, add the above sentencewindow.onloadEvent to initialize the tree menu after the document is loaded. For the complete code, see the source code of the following example.

View results (Example 1)

Distinguish between branches and leaves

In the previous article, we mentioned that the difference between a tree branch and a leaf is whether the node has any subnode. Therefore, we can also consider the method of determining the branches and leaves from this perspective. A more intuitive method is to traverse the DOM tree of the entire tree menu (note the difference between the two "Trees") to see if each node has a subnode, if so, we will assign a dedicated class to this node to differentiate it. Here we use a clever method to determine whether the innerHTML of each node contains a string.'<ul>'. If yes, it obviously has one or more subnodes.

Var trees = getElementsByClassName (document, 'treeview'); for (var I = 0; I <trees. length; I ++) {// first find all the nodes. var nodes = trees [I]. getElementsByTagName ('lil'); // determines whether each node has a subnode for (var j = 0; j <nodes. length; j ++) {if (nodes [j]. innerHTML. toLowerCase (). indexOf ('<ul>')>-1) nodes [j]. className + = 'open ';}}

Here we add a className to each branch:OpenBecause we cannot open and close branches, as long as they are branches, they are open. Of course we will use Close later :). Modify the CSS accordingly and give the branches an icon with a minus sign, indicating that it is open:

.TreeView li.Open{ background:transparent url(opened.gif) 12px 2px no-repeat;}

View results (Example 2)

Highlight selected items

Next we can highlight the selected branches (or leaves. You need to highlight the menu when initializing the menu or clicking a menu item.

It is easier to process during initialization. You can directly assign a special Class to the node to be highlighted, for example,"Selected":

. TreeView li. selected a: link ,. treeView li. selected a: visited ,. treeView li. selected a: hover ,. treeView li. selected a: active {background-color: # 05F; color: # FFF; text-decoration: none;/* remove the underline */cursor: default; /* change the cursor to an ordinary arrow and pretend that it cannot be clicked. */padding: 0 2px;/* You can skip this sentence for the sake of appearance */}

View results (Example 3)

There are several points that need to be further explained:

  1. Before Selector, why should I add.TreeViewIsn't this redundant code?
    In this example, the code is indeed redundant, but in the actual project, there may be various components on a page, such as a menu, the selected menu item is also used.Selected. In this case, you need to first point out the selected items of the component before the selector to avoid conflict. Of course, there are other solutions. For example, if the class here is not named Selectd, it is changed to TreeSelected or something else, but such a human behavior complicate the naming scheme, which I personally do not recommend.
  2. Why is the selector written in four rows?
    Because we have already setaTo improve the priority of the old style, you need to specifya(There are other ways to raise the priority. For details about priority algorithms, see website reconstruction ).
  3. SelectedWhy useliInstead of directly usingaUpper?
    This is not easy to explain, because it is a kind of personal habit to a large extent, but I personally think this is more appropriate. In factliUp oraAt least (the perspective of the presentation layer) is not much different. However, if you jump out of the "presentation layer", you can see it from the perspective of "structural layer, regardless of the tree structure or DOM structure of the menu, a node is composedliTo express,aIt is only a more detailed part of the node. Although I finally wantaSpecify a special style (why not specifyli? You can try it by yourself), but in the XHTML structure, thisclass="Selected"Or write it inli. (God bless me ......)
What is next?

This article is the first time I have added Javascript content. It is not clear whether it is too simple or not. Please leave a message on the right to tell me your thoughts. Starting from the next article, we will start to deploy mouse events and respond to mouse events. Maybe I will add some Javascript object-oriented programming content from the next article, to be determined ...... Hehe ___^

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.