search
HomeWeb Front-endJS TutorialUI components based on web standards - tree menu (2)_javascript skills

从这篇开始,你需要拥有一些Javascript和DOM相关的知识才能顺利地学习下去。由于Javascript和DOM都不是三言两语可以说完的东西,如果你对它们还不熟悉,请先到这里学习一下再继续:Javascript在线教程(英文)、DOM在线教程(英文)。

getElementsByClassName()

  为了从一大堆HTML代码中找出我们的树状菜单(也许有多个),我们先来实现一个通过className找DOM节点的方法:getElementsByClassName。这是对浏览器自有DOM方法的一个简单但实用的扩充。

  此方法有两个参数:ele指出以哪个DOM节点为根节点寻找(也就是说只找ele的子节点),className指出符合条件的节点的class属性中必须包含怎样的className。它的返回值是一个数组,存放了所有符合条件的节点。

<code>function getElementsByClassName(ele,className) {
 //获取所有子节点
 if(document.all){
  var children = ele.all;
 }else{
  var children = ele.getElementsByTagName('*');
 }
 //遍历子节点并检查className属性
 var elements = new Array();
 for (var i = 0; i </code>

  最前面的一个if-else语是为了兼容IE5(IE5不能运行document.getElementsByTagName('*'))。需要注意的是千万不要用浏览器检测的方法来写脚本,而应该直接使用将要用到的语句来测试是否可以执行,如果返回值为nullundefined,那再换一种方法。这样的脚本可以有更好的兼容性,也更健壮。

  elements[elements.length] = child;,这句同样是为了兼容IE5才没有使用数组的push方法。如果你一定要使用push方法,那么可以在执行getElementsByClassName()之前先重载一遍push方法。代码如下:

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

  注:原本我希望getElementsByClassName也能像push方法一样写,比如HTMLElement.prototype.getElementsByClassName = ...。不过实际操作的时候发现在运行时HTMLElement这个对象并不是固定的,每种tag似乎都不一样,只能作罢。如果你有解决方案请告诉我,谢谢。

  现在我们就可以方便地找出页面上所有的树状菜单了:

<code>var trees	= getElementsByClassName(document,'TreeView');
for(var i=0;i<trees.length alert i></trees.length></code>

  最后把上面这几句加到window.onload事件中运行,以便文档一加载完就对树状菜单进行初始化。完整的代码请查看下面例子的源代码。

  查看效果(例1)

区分树枝与树叶

  在上一篇中我们说到树枝和树叶的区别就是这个节点有没有子节点,所以判断树枝和树叶的方法也可以从这个角度来考虑。一个比较直观的方法就是遍历整个树状菜单的DOM树(注意这里两个“树”的区别),看看每个节点是不是拥有子节点,如果有的话我们就给这个节点一个专门的class以示区分。我们这里用一种比较取巧的方法,就是判断各个节点的innerHTML中有没有出现字符串'<ul>'</ul>。如果有的话,那么很显然它拥有一个或多个子节点。

<code>var trees	= getElementsByClassName(document,'TreeView');
for(var i=0;i<trees.length var nodes="trees[i].getElementsByTagName('LI');" for j="0;j<nodes.length;j++){" if>') > -1)
   nodes[j].className += 'Open';
 }
}
</trees.length></code>

  这里给每个树枝加了一个className:Open,因为我们现在还不能打开关闭树枝,所以只要是树枝那就是open的。当然后面我们会用到Close的:)。相应的修改一下CSS,给树枝一个带减号的图标,表示它是打开的:

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

  查看效果(例2)

高亮选中项

  接下来实现把当前选中的树枝(或树叶)高亮的功能。有两个时候需要高亮:菜单初始化的时候和点击某个菜单项的时候。

  初始化的时候比较容易处理,直接给需要高亮的节点一个特殊的Class即可,比如“Selected”:

<code>.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;/*去除下划线*/
 cursor:default;/*让光标变为普通箭头,假装是不能点的^_^*/
 padding:0 2px;/*为了美观考虑,也可以不要这句*/
}</code>

  查看效果(例3)

  这里有几点可能还需要补充说明一下:

    Why do we need to add
  1. in front of the selector? Isn’t this redundant code? .TreeView is indeed redundant code in this example, but in actual projects, there may be various components on a page, such as a menu, and the selected menu item is also represented by
    . At this time, you need to indicate what component is selected in front of the selector to prevent conflicts. Of course there are other solutions, such as not naming the class here Selectd, but changing it to TreeSelected or something else, but this artificially complicates the naming scheme, and I personally do not recommend this. .SelectedWhy is the selector written in four lines?
  2. Because we have set the style of
    before, in order to overload the old style to improve the priority, we need to specify the four pseudo states of a (there are other ways to improve the priority, about the priority algorithm , described in detail in the book "aWebsite Reconstruction"). Why should
  3. be used on Selected instead of directly on li? aThis is another place that is not easy to explain, because to a large extent it is a personal habit, but I personally feel that this is more appropriate. In fact, it’s okay to write on
    or li, at least it won’t look much different (from the perspective of the presentation layer), but if you jump out of the “presentation layer” and stand on From the perspective of the "structural layer", regardless of the tree structure or DOM structure of this menu, a node is expressed by a a, and li is just a more detailed part of this node. Although I ultimately hope to assign a special style to a (why not assign it to a? You can try it yourself), in terms of XHTML structure, it is more appropriate to write this li on class="Selected" . (God forbid I made it clear...) li
What will you talk about next?

This article is the first time I have added Javascript content. It is not clear whether it is shallow or deep. Please leave a message on the right to tell me your thoughts. Starting from the next article, we start to get into the content of deploying mouse events and responding to mouse events. Maybe I will add some Javascript object-oriented programming content from the next article, to be determined... hehe^_^

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.