Home Web Front-end JS Tutorial Implementing universal tabs based on JavaScript (strong versatility)_javascript skills

Implementing universal tabs based on JavaScript (strong versatility)_javascript skills

May 16, 2016 pm 03:21 PM

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> 
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles