search
HomeWeb Front-endJS TutorialFour ways to implement tab switching in javascript

This article mainly introduces four ways to implement tab switching in JavaScript, and evaluates each method. Interested friends can refer to it

Tab switching is very common in web pages. Therefore, 4 implementation methods have been summarized recently.
First, write the tab frame and add the simplest style. The code is as follows:

<!DOCTYPE html>
 <html>
 <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
 *{
 padding: 0;
 margin: 0;
 }
 li{
  list-style: none;
  float:left;
 }
 #tabCon{
  clear: both;
 }
 </style>
 </head>
 <body>
 <p id="tanContainer">
  <p id="tab">
  <ul>
   <li>标题一</li>
   <li>标题二</li>
   <li>标题三</li>
   <li>标题四</li>
  </ul>
  </p>
  <p id="tabCon">
  <p>内容一</p>
  <p>内容二</p>
  <p>内容三</p>
  <p>内容四</p>
  </p>
 </p>
 </body>
 </html>

The current display effect is as follows:

Four ways to implement tab switching in javascript

The four tab titles and four content areas are all displayed on the page. Now we need to achieve the tab switching effect, that is, click title one, content one will be displayed, and other content will be displayed. Not displayed; click title two, content two is displayed, and other content is not displayed...
Then, the overall idea is very simple, bind events to four titles, and when triggered, the corresponding content is displayed, and other content is hidden.

Method 1: The content corresponding to the clicked title is displayed, and the content corresponding to the non-clicked title is hidden. The code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <style>
 *{
  padding: 0;
  margin: 0;
 }
 li{
  list-style: none;
 }
 </style>
 <script>
 function tab(pid){
  var tabs=["tab1","tab2","tab3","tab4"];
  for(var i=0;i<4;i++){
   if(tabs[i]==pid){
    document.getElementById(tabs[i]).style.display="block";
  }else{
    document.getElementById(tabs[i]).style.display="none";
  }
  }
 }
 </script>
</head>
 <body>
 <p id="tanContainer">
  <p id="tabNav">
  <ul>
   <li onclick="tab(&#39;tab1&#39;)">标题一</li>
   <li onclick="tab(&#39;tab2&#39;)">标题二</li>
   <li onclick="tab(&#39;tab3&#39;)">标题三</li>
   <li onclick="tab(&#39;tab4&#39;)">标题四</li>
  </ul>
  </p>
  <p id="tab">
   <p id="tab1">内容一</p>
  <p id="tab2">内容二</p>
   <p id="tab3">内容三</p>
  <p id="tab4">内容四</p>
  </p>
 </p>
 </body>
 </html>

##Method 2: First set all content to be hidden, then click on the title pair The content used is displayed. The code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <style>
 *{
  padding: 0;
  margin: 0;
 }
 li{
  list-style: none;
 float:left;
 }
 #tabCon{
  clear: both;
 }
 #tabCon_1{
 display: none;
 }
 #tabCon_2{
  display: none;
 }
 #tabCon_3{
 display: none;
 }
 </style>
 <script>
 function changeTab(tabCon_num){
 for(i=0;i<=3;i++) { 
  document.getElementById("tabCon_"+i).style.display="none"; //将所有的层都隐藏 
  } 
  document.getElementById("tabCon_"+tabCon_num).style.display="block";//显示当前层 
 } 
 </script>
 </head>
 <body>
 <p id="tanContainer">
  <p id="tab">
  <ul>
   <li onclick="changeTab(&#39;0&#39;)">标题一</li>
   <li onclick="changeTab(&#39;1&#39;)">标题二</li>
   <li onclick="changeTab(&#39;2&#39;)">标题三</li>
   <li onclick="changeTab(&#39;3&#39;)">标题四</li>
  </ul>
 </p>
  <p id="tabCon">
  <p id="tabCon_0">内容一</p>
  <p id="tabCon_1">内容二</p>
  <p id="tabCon_2">内容三</p>
  <p id="tabCon_3">内容四</p>
 </p>
 </p>
 </body>
 </html>

##Method 3: Show and hide through class control. First, set the hidden display of all content to none, and set the display of the class to block. Traverse all title nodes and content nodes. After clicking the title, the title node and the corresponding content node have the class, and the others do not. The code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <style>
 *{
  padding: 0;
  margin: 0;
 }
 li{
  list-style: none;
  float:left;
 }
 #tabCon {
  clear: both;
 }
 #tabCon p {
  display:none;
 }
 #tabCon p.fp {
  display:block;
 }
 </style>
 </head>
 <body>
 <p id="tanContainer">
  <p id="tab">
  <ul>
   <li class="fli">标题一</li>
   <li>标题二</li>
   <li>标题三</li>
   <li>标题四</li>
  </ul>
  </p>
  <p id="tabCon">
  <p class="fp">内容一</p>
  <p>内容二</p>
  <p>内容三</p>
  <p>内容四</p>
 </p>
 </p>
 </body>
 <script>
 var tabs=document.getElementById("tab").getElementsByTagName("li");
 var ps=document.getElementById("tabCon").getElementsByTagName("p");

 for(var i=0;i<tabs.length;i++){
  tabs[i].onclick=function(){change(this);}
 }

 function change(obj){
 for(var i=0;i<tabs.length;i++){
  if(tabs[i]==obj){
  tabs[i].className="fli";
  ps[i].className="fp";
 }else{
  tabs[i].className="";
  ps[i].className="";
  }
  }
 } 
 </script>
 </html>

The disadvantage of this method is that there can no longer be a p tag under the p of the content block.

Method 4: Instead of js, use "input:checked" to switch tabs. First hide all content and display the selected content. The code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>input:checked实现tab切换</title>
 <style>
 input{
 opacity: 0;/*隐藏input的选择框*/
 }
 label{
 cursor: pointer;/*鼠标移上去变成手状*/
 float: left;
 }
 label:hover{
 background: #eee;
 }
 input:checked+label{
 color: red;
 }
 /*选择前面有.tabs input:nth-of-type(x):checked的.panels .panel:nth-child(x)*/
 .tabs input:nth-of-type(1):checked~.panels .panel:nth-child(1),
 .tabs input:nth-of-type(2):checked~.panels .panel:nth-child(2){
 opacity: 1;
 }
 .panel{
 opacity: 0;
 position: absolute;/*使内容区域位置一样*/
 }
 </style>
 </head>
 <body>
 <p class="tabs">
  <input checked id="one" name="tabs" type="radio">
  <label for="one">标题一</label>
 
  <input id="two" name="tabs" type="radio">
  <label for="two">标题二</label>
 
  <p class="panels">
   <p class="panel">
   <p>内容一</p>
   </p>
   <p class="panel">
   <p>内容二</p>
   </p>
  </p>
 </p>
 </body>
 </html>

The disadvantage of this method is that switching between different areas can only be done by clicking.

The above is the tab switching implementation method summarized for everyone. I hope it will be helpful to everyone's learning. Follow this idea and start making your own tab switching special effects.

For more related articles on the four methods of tab switching using javascript, please pay attention to the PHP Chinese website!

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

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software