Home Web Front-end JS Tutorial How to use JavaScript to achieve the finger sliding switching effect of tab content while limiting it to the container?

How to use JavaScript to achieve the finger sliding switching effect of tab content while limiting it to the container?

Oct 20, 2023 am 11:31 AM
Tab javascript implementation Finger sliding switching effect In-container restrictions

如何使用 JavaScript 实现选项卡内容的手指滑动切换效果同时限制在容器内?

How to use JavaScript to achieve the finger sliding switching effect of tab content while limiting it to the container?

Tabs are a common web page layout that can switch to display different content in the same area. Compared with the traditional click switching method, the finger sliding switching effect is more friendly and intuitive on mobile devices. This article will introduce how to use JavaScript to implement the finger sliding switching effect of tab content and limit it to the container.

First, we need an HTML structure to host the tab content. Assume that our tab has three labels, each label corresponds to a content area, the HTML structure can be as follows:

<div class="container">
  <div class="tabs">
    <div class="tab" id="tab1">标签1</div>
    <div class="tab" id="tab2">标签2</div>
    <div class="tab" id="tab3">标签3</div>
  </div>
  <div class="content">
    <div class="panel" id="panel1">内容1</div>
    <div class="panel" id="panel2">内容2</div>
    <div class="panel" id="panel3">内容3</div>
  </div>
</div>
Copy after login

In the above code, .tabs is used to carry the tab label , .content is used to carry the tab content, .tab and .panel are the specific tab labels and content.

Next, we need to use CSS to style the tab container, including container size, tab label style, and content area style. In order to achieve the finger sliding effect, we also need to use overflow: hidden to hide content beyond the scope of the container. The CSS style can look like this:

.container {
  width: 300px;
  height: 200px;
  overflow: hidden;
}

.tabs {
  display: flex;
}

.tab {
  flex: 1;
  text-align: center;
}

.content {
  width: 300%;
  display: flex;
}

.panel {
  flex: 1;
  text-align: center;
}
Copy after login

Next, we can use JavaScript to implement the finger slide switching effect and limit it to the container. We use touchstart, touchmove and touchend events to listen for finger sliding operations.

const container = document.querySelector('.container');
const tabs = document.querySelectorAll('.tab');
const panels = document.querySelectorAll('.panel');

let startX = 0;
let currentX = 0;

container.addEventListener('touchstart', (event) => {
  startX = event.touches[0].clientX;
});

container.addEventListener('touchmove', (event) => {
  event.preventDefault();
  currentX = event.touches[0].clientX;
});

container.addEventListener('touchend', () => {
  const deltaX = currentX - startX;
  const threshold = container.offsetWidth / 3;

  if (deltaX > threshold && currentIndex > 0) {
    currentIndex--;
  } else if (deltaX < -threshold && currentIndex < tabs.length - 1) {
    currentIndex++;
  }

  const translateX = -currentIndex * 100;

  tabs.forEach((tab) => tab.classList.remove('active'));
  panels.forEach((panel) => panel.classList.remove('active'));

  tabs[currentIndex].classList.add('active');
  panels[currentIndex].classList.add('active');

  container.querySelector('.content').style.transform = `translateX(${translateX}%)`;
});
Copy after login

In the above code, we first select the DOM element through the querySelector method, and then use the variables startX and currentX to record when the finger slides The starting and current abscissa. In the touchstart event, we use event.touches[0].clientX to get the abscissa when the finger starts sliding. In the touchmove event, we obtain the current abscissa of the finger through event.touches[0].clientX and use the preventDefault() method to cancel the default sliding event . In the touchend event, we calculate the horizontal offset of the finger slide deltaX, and determine whether the tab needs to be switched based on the threshold of threshold. Finally, we switch to the correct tab and content by manipulating the transform properties of the tab style and content area.

For complete sample code, please refer to the following link:
[https://codepen.io/](https://codepen.io/)

In summary, we You can use JavaScript to implement the finger sliding switching effect of tab content and limit it to the container. By listening to touchstart, touchmove and touchend events, we can implement the function of switching tabs by finger sliding, and restrict sliding within the container through CSS styles. This type of interaction is more friendly and intuitive on mobile devices, improving user experience.

The above is the detailed content of How to use JavaScript to achieve the finger sliding switching effect of tab content while limiting it to the container?. For more information, please follow other related articles on the PHP Chinese website!

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)

Fix: ERR_ADDRESS_UNREACHABLE error in Google Chrome Fix: ERR_ADDRESS_UNREACHABLE error in Google Chrome May 15, 2023 pm 06:22 PM

Several Windows users have complained that when they try to access some websites on Google Chrome browser on their systems, they are unable to access the web pages. It also displays a message on the browser saying "The site cannot be reached" with error code ERR_ADDRESS_UNREACHABLE. There could be many potential reasons behind this issue, it could be due to website server issues, proxy server settings, unstable internet connection, etc. If you encounter similar problems, don't panic. After deeply analyzing the problem in this article, we got a bunch of solutions. Before proceeding, try the following workarounds: Try checking if the user is trying to access the site from other devices and there are no issues, then this

How to fix preview pane not working in Windows 11 How to fix preview pane not working in Windows 11 Apr 24, 2023 pm 06:46 PM

One of the features that comes with Windows File Explorer is the preview pane, which displays a preview of the file you selected. This means you can view the contents of the file before opening it. The preview pane of File Explorer provides previews for different types of files such as Office-related documents, PDFs, text files, images, and videos. It usually works fine, but sometimes the file preview isn't available. Recently, many Windows 11 users have raised the issue that File Explorer’s preview pane is not working and they are unable to view file previews. Are you facing the issue of preview pane not working on your Windows computer? Then, continue reading this article. Here we have compiled a list of fixes that can help you fix

Can't use MSI Afterburner in Windows 11? Try the following fixes. Can't use MSI Afterburner in Windows 11? Try the following fixes. May 09, 2023 am 09:16 AM

MSIAfterburner is an overclocking tool suitable for most graphics cards. Apart from that, you can also use it to monitor the performance of your system. But some users reported that MSIAfterburner is not working in Windows 11. This may be due to several reasons, which we discuss in the following sections. However, when this happens, it prevents you from changing the performance or monitoring it while playing the game. As expected, this poses a significant challenge to gamers. That’s why we’ve dedicated this tutorial to help you understand the issue and walk you through the most effective fixes for MSIAfterburned not working in Windows 11 issue.

Fix: VAN 1067 error when running Valorant on Windows 11 Fix: VAN 1067 error when running Valorant on Windows 11 May 22, 2023 pm 02:41 PM

The operating system looks much better than its predecessor and has gamer-oriented features like AutoHDR and DirectStorage, but Valorant players have had some trouble launching the game. This is not the first issue faced by gamers earlier, Valorant not opening on Windows 11 is another issue plaguing them but we have covered the ways to fix it. Now it seems that Valorant players who switched to Windows 11 are facing issues due to Secure Boot and TPM2.0 services, which causes the game menu to only show an exit option while running. Many users are getting the VAN1067 error, but it shouldn't be a cause for alarm

How to disable video autoplay in Opera browser? How to disable video autoplay in Opera browser? Apr 22, 2023 pm 10:43 PM

The latest version of the Opera browser includes a new automatic video popup feature. Using this feature, you will notice that the video will pop up automatically when you navigate to another tab in the browser. It has been noticed that this pop-up video can be resized and moved around the screen. When you navigate back to the Videos tab, it resumes and the floating window disappears. The video pop-up feature is useful for multitasking users who like to watch videos while working. However, not every Opera user will like this automatic video popup feature. If you are one of those Opera browser users who are annoyed by videos popping up every time you change tabs, then you have found the right post. Here we detail how to disable this popup in Opera

DirectX function GetDeviceRemovedReason fails with error DirectX function GetDeviceRemovedReason fails with error May 17, 2023 pm 03:38 PM

Almost every high-end game we play relies on DirectX to run efficiently. However, some users reported encountering the DirectX function GetDeviceRemovedReasonfailedwith followed by the error reason. The above reasons are not self-evident to the average user and require some level of research to determine the root cause and the most effective solution. To make things easier, we've dedicated this tutorial to this problem. In the following sections, we will help you identify the potential causes and walk you through the troubleshooting steps to eliminate the DirectX function GetDeviceRemovedReasonfailedwitherror. what causes

To fix this, you need to use an interactive window station To fix this, you need to use an interactive window station Apr 24, 2023 pm 11:52 PM

This operation requires an interactive window station which is a rather strange bug. Software windows that allow users to interact with the app are not open, you need to enable them. This bug has been linked to the 2021 Printing Nightmare vulnerability. However, it continues to this day, affecting your computer and device drivers. Fortunately, it's easy to fix. Why does this error occur in the first place? Before describing how to fix this error, be sure to list the causes of this error. This way, you can take the necessary steps to ensure it doesn't happen again. Corrupted files are messing up your computer files – Corruption can be caused by a variety of reasons, from malware to power outages. It is recommended that you run an SFC scan. You have an overzealous antivirus app – antivirus software sometimes blocks

How to Optimize Internet Connection Speed ​​in Windows 11 How to Optimize Internet Connection Speed ​​in Windows 11 Apr 23, 2023 pm 10:46 PM

How to solve the problem of slow network speed in Windows 11? 1. Restart your computer Navigate to the desktop and press Alt+F4 to activate the "Shut down Windows" box. Click the drop-down menu and select Restart from the list of options. Next, click OK. For most problems you encounter in Windows 11, one of the most effective solutions is to simply restart your computer. If it is a background process or error that is causing the problem, restarting the operating system will eliminate it, thus fixing the error. After restarting the computer, check whether the network speed problem of Windows 11 is resolved. 2. Make sure the PC is within range of the router (Wi-Fi network) In the case of a wireless network, the farther the device is from the router, the slower the internet speed will be

See all articles