search
HomeWeb Front-endJS TutorialImplementing universal tabs based on JavaScript (strong versatility)_javascript skills

Tabs are used in a large number of websites. Although the forms are different, the purpose to be achieved is the same. They are generally used for classification or to save web page space. They are considered a sharp tool. Here is one The code example of the tab is very versatile, so I will share it with you below.

The code example is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.jb51.net/" />
<title>js实现的可以通用的选项卡代码实例</title>
<style type="text/css">
body {text-align:center;}
.tab1, .tab2 
{
width:350px;
margin:0 5px;
background:#CC9933;
opacity:0.5;
border-radius:5px 5px 5px 5px;
box-shadow:#CCC 4px 4px 4px;
text-align:left;
float:left;
display:inline;
}
.name 
{
list-style:none;
overflow:hidden;
}
.name li 
{
width:90px;
font:bold 16px/30px Verdana, Geneva, sans-serif;
background:#669900;
text-align:center;
border-radius:5px 5px 5px;
margin-right:5px;
float:left;
display:inline;
cursor:pointer;
}
li.selected{background:#FF9900;}
.content li 
{
height:500px;
display:none;
}
</style>
<script type="text/javascript">
/** 
* 事件处理通用函数
*/
var EventUtil={
getEvent:function(event)
{
return event &#63; event : window.event;
},
getTarget:function(event)
{
return event.target||event.srcElement;
},
addHandler:function(element,type,handler)
{
if(element.addEventListener)
{
element.addEventListener(type,handler,false);
}
else if(element.attachEvent)
{
element.attachEvent("on"+type,handler);
}
else
{
element["on"+type] = handler;
} 
}
};
/**
* 选项卡通用函数
*/
// 传入参数inClassName设定为绑定的选项卡类名,参数triggerType设定为触发切换的类型
function tabSwitch(inClassName,triggerType){
//取得全部选项卡区域
if(document.querySelectorAll)
{
var tabs=document.querySelectorAll("."+inClassName);
}
else
{
var divs=document.getElementsByTagName("div");
var tabs = new Array();
for(var k=0,lenDiv=divs.length;k<lenDiv;k++)
{
if(divs[k].className.indexOf(inClassName)>-1)
{
tabs.push(divs[k]);
}
}
}
//为每个选项卡建立切换功能
for(var j=0,len=tabs.length; j<len; j++)
{
//获取标题和内容列表
var tab = tabs[j];
//使用私有作用域为每个选项卡建立切换
(function(){
var nameUl = tab.getElementsByTagName("ul")[0];
var content = tab.getElementsByTagName("ul")[1];
//初始化选项卡
nameUl.getElementsByTagName("li")[0].className = "selected";
content.getElementsByTagName("li")[0].style.display = "block";
//添加事件委托
EventUtil.addHandler(nameUl,triggerType,function(event)
{
//获取事件对象
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
//选项卡切换
if(target.nodeName.toLowerCase() == "li")
{
//分别取得标题列表项和内容列表项
var nameList = nameUl.getElementsByTagName("li");
var contentList = content.getElementsByTagName("li");
//标题添加selected类,并显示内容
for(var i=0,len=nameList.length; i<len; i++)
{
nameList[i].className = "";
contentList.style.display = "none";
if(nameList == target)
{
nameList.className = "selected";
contentList.style.display = "block";
}
}
}
});
})();
}
}
window.onload=function()
{
//设置选项卡切换方式
tabSwitch("tab1","click");
tabSwitch("tab2","mouseover");
}
</script>
</head>
<body>
<div class="tab1">
<ul class="name">
<li>项目一</li>
<li>项目二</li>
<li>项目三</li>
</ul>
<ul class="content">
<li>类为<em>"tab1"</em>项目一内容,通过<em>"click"</em>触发</li>
<li>类为<em>"tab1"</em>项目二内容,通过<em>"click"</em>触发</li>
<li>类为<em>"tab1"</em>项目三内容,通过<em>"click"</em>触发</li>
</ul>
</div>
<div class="tab1">
<ul class="name">
<li>项目一</li>
<li>项目二</li>
<li>项目三</li>
</ul>
<ul class="content">
<li>类为<em>"tab1"</em>项目一内容,通过<em>"click"</em>触发</li>
<li>类为<em>"tab1"</em>项目二内容,通过<em>"click"</em>触发</li>
<li>类为<em>"tab1"</em>项目三内容,通过<em>"click"</em>触发</li>
</ul>
</div>
<div class="tab2">
<ul class="name">
<li>项目一</li>
<li>项目二</li>
<li>项目三</li>
</ul>
<ul class="content">
<li>类为<em>"tab2"</em>项目一内容,通过<em>"mouseover"</em>触发</li>
<li>类为<em>"tab2"</em>项目二内容,通过<em>"mouseover"</em>触发</li>
<li>类为<em>"tab2"</em>"项目三内容,通过<em>"mouseover"</em>触发</li>
</ul>
</div>
</body>
</html> 

The above code implements the function of the tab. The following is a brief introduction to the implementation process.

1. Implementation principle:

It may seem like a lot of code, but the principle is actually very simple. We will only briefly introduce the principle here. For details, you can refer to the code comments and rely on your own thinking. In the default state, the title of the tab is displayed, and the first title is assigned the specified style class. Only the first tab content is displayed, and the others are hidden. This is achieved. In the default state The first selected effect. Each tab title will be registered with a specified event handler. When a click or swipe operation is performed, the corresponding switch can be realized, mainly through traversal. I won’t introduce it in detail here. Please refer to the code comments.

2. Code comments:

1.var EventUtil={}, declares an object literal, which internally implements the operations of obtaining event objects, event source objects and event processing function bindings, and is compatible with major browsers.
2. getEvent:function(event){return event ? event : window.event;}, get the event object, compatible with all major browsers.
3.getTarget:function(event){return event.target||event.srcElement;}, obtain the event source object, compatible with major browsers.
4.addHandler:function(element,type,handler){}, the registered event processing function is compatible with all major browsers.
5.function tabSwitch(inClassName,triggerType){}, this function can register the specified event processing function for the specified object. It has two parameters. The first parameter is the style class name, which is used to obtain the object with such name. Two are event types.
6.if(document.querySelectorAll), used to determine whether the browser supports the querySelectorAll function.
7.var tabs=document.querySelectorAll("."+inClassName), if supported, obtains the object with the specified class name.
8.var divs=document.getElementsByTagName("div"), get the collection of div objects.
9.var tabs=new Array(), creates an array to store div objects with specified style classes.
10.for(var k=0,lenDiv=divs.length;k 11.if(divs[k].className.indexOf(inClassName)>-1), if the style class name of the div contains the specified style class name.
12. tabs.push(divs[k]), save this div into the array.
13.for(var j=0,len=tabs.length;j 14.var tab=tabs[j], assign the reference of a div object to tab.
15.(function(){})(), declare an anonymous function and execute it.
16.var nameUl=tab.getElementsByTagName("ul")[0], get the first one in the ul collection, which is the title part of the tab.
17.var content=tab.getElementsByTagName("ul")[1], get the content part of the tab.
18.nameUl.getElementsByTagName("li")[0].className="selected", set the style class value of the first title in the tab title part to selected.
19.content.getElementsByTagName("li")[0].style.display="block", set the first content part of the tab to display.
20.EventUtil.addHandler(nameUl,triggerType,function(event){}), this function is the core part of implementing the tab and has three parameters. The first parameter is the ul object of the title part, and the second is the event type. , the third function is the event handling function to be registered.
21.var event=EventUtil.getEvent(event), get the event object.
22.var target=EventUtil.getTarget(event), get the event source object.
23.if(target.nodeName.toLowerCase()=="li"), determine whether the label name of the event source object is li.
24.var nameList=nameUl.getElementsByTagName("li"), obtains the collection of li elements in the tab title part.
25.var contentList=content.getElementsByTagName("li"), get the combination of li elements in the content part of the tab.
26.for(var i=0,len=nameList.length;i 27.nameList.className="", clear the style class of each title li element.
28.contentList.style.display="none", hide the li in the content part of each tab.
29.if(nameList==target), if the title li of the specified index is the event source object, that is, the li currently clicked by the mouse or the li the mouse slides over.
30.nameList.className="selected", then add the specified style class to it.
31.contentList.style.display="block" will display the content li corresponding to the index.

The above content is introduced in relatively detail, with code and comments. I hope it will be helpful to everyone in learning about js implementation of tabs.

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
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.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools