search
HomeWeb Front-endJS TutorialNative JS realizes various effects of Tab tab

Native JS realizes various effects of Tab tab

Feb 23, 2018 pm 02:01 PM
javascriptEffect

Some time ago I wrote several articles about the understanding and usage of css attributes. Today I will not share the css attributes. I will share with you an effect that we use more in actual work-the Tab option. card effect. First, let’s take a look at what the Tab effect looks like. Taking QQ News as an example, it has the following effect:

Native JS realizes various effects of Tab tab

When the mouse slides to When the relevant title is on, the content corresponding to the title will appear. This is the sliding switching effect of the Tab tab. The Tab tab effect also includes delayed switching and automatic switching. Effect. Today, let’s learn these three effects of the Tab tab with you.

2. Common codes for the three effects

The three effects are based on the following common html structure and css style:
Native JS realizes various effects of Tab tab

In the html code, use two p's to contain the title and content respectively. The number of titles and the number of content need to be the same. The detailed html code and css code are as follows:

html code

<p>
  </p><p>
    </p>
     

    

      

         

      

            
  •                        [             通知             ]                      “滥发”即将换新         
  •         
  •                        [             通知             ]                      比特币严管啦         
  •         
  •                        [             通知             ]                      禁发商品名录         
  •         
  •                        [             通知             ]                      商品熟悉限制         
  •       
         

      

            
  •                        [             聚焦             ]                      金牌卖家再启航         
  •         
  •                        [             功能             ]                      橱窗规则升级啦         
  •         
  •                        [             话题             ]                      又爱又恨优惠券         
  •         
  •                        [             工具             ]                      购后送店铺红包         
  •       
         

      

         

      

       

css code

*{
    margin: 0;
    padding: 0;
    list-style: none;
    font-size: 12px;
    box-sizing: border-box;
}
.notice{
    width: 302px;
    height: 100px;
    margin: 10px;
    border: 1px solid #eee;
    overflow: hidden;
}
.notice-title{
    height: 26px;
    background: #f7f7f7;
}

.notice-title li{
    float: left;
    width: 60px;
    line-height: 26px;
    text-align: center;
    overflow: hidden;
    background: #fff;
    border-bottom: 1px solid #eee;
    background: #f7f7f7;
}

.notice li a:link,
.notice li a:visited{
    text-decoration: none;
    color: #000;
}

.notice li a:hover{
    color: #f90;
}
.notice-title li.select{
    background: #fff;
    border-bottom-color: #fff;
    border-left: 1px solid #eee;
    border-right: 1px solid #eee;
    font-weight: bold;
}
.notice-title li:first-child.select{
    border-left: none;
}
.notice-title li:last-child.select{
    border-right: none;
}

.notice-content .mod{
    padding: 12px 5px;
}
.notice-content .mod ul{
    width: 300px;
    font-size: 0;
}
.notice-content .mod ul li{
    display: inline-block;
    width: 145px;
    height: 25px;
    line-height: 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

3. Slide Analysis of the switching effect principle

Sliding switching effect, as the name suggests, when the mouse slides over, the content under the title is displayed. It is necessary to set the style of the current title to the selected state (add the css style selected by the title, in this case, add the select style class), and at the same time set the content under the title to be displayed, that is, set the style display:block, and the content under other headings is set to be hidden, that is, the style is set to display:none. The detailed javascript code is as follows:

function $(id) {
    return typeof id==='string'? document.getElementById(id):id;
}
//获取鼠标滑过或点击的标签和要切换内容的元素
var titles = $('notice-title').getElementsByTagName('li'),
    ps = $('notice-content').getElementsByTagName('p');
if(titles.length != ps.length){
  return;
}
// 遍历titles下的所有li
for(var i = 0; i <p> If you need to achieve the effect of <strong>click switching</strong>, you only need to change <code>onmouseover</code> to <code> onclick</code> is enough. </p><p>The effect in the browser is as follows: </p><p><span class="img-wrap"><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/947a04b099e04a1fa765b4c4cc7070ad-2.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Native JS realizes various effects of Tab tab" ></span></p><p>When the mouse passes over the relevant title, the corresponding content in the title will be displayed. </p><h2 id="Analysis-of-the-principle-of-delayed-switching-effect">4. Analysis of the principle of delayed switching effect</h2><p><strong>Delayed switching effect</strong>, as the name suggests, it means that the relevant content under the title will be displayed after the mouse slides over the title for a certain period of time. It is familiar. Students of <code>javascript</code> know that we can use the <code>setTimeout</code> function to delay a certain period of time, and then modify the related titles and content to be displayed or hidden. Its <code>javascript</code> code is not much different from <strong>sliding switching effect</strong>. What we need to modify is to first determine whether the timer <code>timer</code> exists. If it exists, we need to clear the timer<code>timer</code>, otherwise there will be multiple timers, causing the switching effect to be disordered, and then put the code that modifies the title style and title content into the <code>setTimout</code> function. </p><pre class="brush:php;toolbar:false">var timer = null;

var list = $('notice-title').getElementsByTagName('li'),
    ps = $('notice-content').getElementsByTagName('p');
if(list.length != ps.length){
  return;
}
for(var i = 0; i <p>The effect in the browser is as follows: </p><p><span class="img-wrap"><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/947a04b099e04a1fa765b4c4cc7070ad-3.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Native JS realizes various effects of Tab tab" ></span></p><p>When the mouse slides over the title, there is always a certain interval of time. The title content appears later. </p><h2 id="Analysis-of-the-principle-of-automatic-switching-effect">5. Analysis of the principle of automatic switching effect</h2><p><strong>Automatic switching effect</strong>, as the name suggests, means that tabs can be automatically switched. In <code>javascript</code>, we can use <code>setInterval</code> to achieve this effect. The specific steps are as follows: </p><ol class=" list-paddingleft-2">
<li><p> By default, the first title is selected, the content under the first title is displayed, and an id is set for each title; </p></li>
<li><p> Determine whether the timer exists. If it exists, clear the timer; </p></li>
<li><p>Use the <code>setInterval</code> function to set the timer every certain time (in this example The set time is 2s) Execute the function autoPlay. In the autoPlay function, change the subscript <code>index</code> of the displayed title. If the value of the subscript <code>index</code> is greater than or equal to the number of titles, then Set the value of the displayed subscript <code>index</code> to 0; </p></li>
<li><p> Set the subscript of the title equal to the displayed subscript <code>index</code> and increase the value <code> selected</code> class, and set the subscript of the content equal to the display subscript <code>index</code> value to display (<code>display:block</code>), and modify the rest of the title content to hide (<code> display:none</code>);</p></li>
</ol><pre class="brush:php;toolbar:false">//当前高亮显示的页签索引
var index = 0;
var timer = null;
//获取所有的页签和要切换的内容
var list = $('notice-title').getElementsByTagName('li'),
    ps = $('notice-content').getElementsByTagName('p');

//遍历每一个页签并且给他们绑定事件
for(var i = 0; i = list.length) {
    index = 0;
  }
  changeOption(index);
}

function changeOption(curIndex) {
  // console.log(curIndex);
  for(var j = 0; j <p> has the following effect in the browser:</p><p><span class="img-wrap"><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/3b9682f9b668eab4890ff83825e0f869-4.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Native JS realizes various effects of Tab tab" ></span></p><p> It can be found that tabs can be automatically switched at certain intervals. </p><h2 id="Written-at-the-end">6. Written at the end</h2><p>Okay, today I will share with you the three switching effects of the Tab tab. I hope it will serve as a warm-up for everyone and help you master the principle of the Tab tab. Its sliding switching, delayed switching, and automatic switching effects are relatively easy to achieve. </p><p>Related recommendations: <br></p><p><a href="http://www.php.cn/js-tutorial-385400.html" target="_self">jQuery mobile Tab tab effect implementation method</a></p><p><a href="http://www.php.cn/js-tutorial-385201.html" target="_self">Detailed explanation of JavaScript plug-in Tab</a></p><p><a href="http://www.php.cn/js-tutorial-382851.html" target="_self">About JavaScript plug-in Tab effect sharing</a></p><p class="comments-box-content"><br></p>

The above is the detailed content of Native JS realizes various effects of Tab tab. For more information, please follow other related articles on 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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor