如何将jQuery实现的标签切换功能改写为原生JavaScript?
Hey there! I totally get where you're coming from—making the switch from jQuery to vanilla JS can feel a bit tricky at first, but breaking down familiar features like tab switching is a great way to build that understanding. Let's walk through how to recreate your tab functionality with plain JavaScript, then break down the key differences between the two approaches.
Full Vanilla JS Implementation
First, here's the complete code that matches your jQuery version's behavior (including the fade-in animation):
<!DOCTYPE html> <html> <head> <style> .tabContent { display: none; transition: opacity 0.5s ease; /* Adds smooth fade effect */ } #tab1 { display: block; opacity: 1; } .tabContainer .current { /* Keep your existing highlight styles here */ font-weight: bold; color: #007bff; } </style> </head> <body> <div class="tabWrapper"> <ul class="tabContainer"> <li class="current"><a href="#tab1">Tab 1</a></li> <li><a href="#tab2">Tab 2</a></li> <li><a href="#tab3">Tab 3</a></li> </ul> <div id="tab1" class="tabContent">Tab 1 Content</div> <div id="tab2" class="tabContent">Tab 2 Content</div> <div id="tab3" class="tabContent">Tab 3 Content</div> </div> <script> // Wait for the DOM to be fully loaded (more reliable than setTimeout) document.addEventListener('DOMContentLoaded', function() { // Grab all tab links const tabLinks = document.querySelectorAll('.tabContainer a'); // Add click event listener to each link tabLinks.forEach(link => { link.addEventListener('click', function(e) { // Stop the default link behavior (jumping to the anchor) e.preventDefault(); // Handle active tab styling const activeTabLi = this.parentElement; // Add "current" class to the clicked tab's parent li activeTabLi.classList.add('current'); // Remove "current" class from all sibling li elements Array.from(activeTabLi.parentElement.children).forEach(li => { if (li !== activeTabLi) { li.classList.remove('current'); } }); // Handle tab content visibility const activeTabId = this.getAttribute('href'); const activeTabContent = document.querySelector(activeTabId); const allTabContents = document.querySelectorAll('.tabContent'); // Hide all tab contents first allTabContents.forEach(content => { content.style.display = 'none'; content.style.opacity = 0; }); // Fade in the active tab content activeTabContent.style.display = 'block'; // Trigger a reflow to make the opacity transition work void activeTabContent.offsetWidth; activeTabContent.style.opacity = 1; }); }); }); </script> </body> </html>
Key Differences Between jQuery and Vanilla JS
Let's break down how this differs from your jQuery code to help you spot patterns:
- Selectors: jQuery's
$()wraps elements in a jQuery object, while vanilla JS usesquerySelector()/querySelectorAll()to get raw DOM elements. For collections (like all tab links), you'll loop through them withforEach()(modern browsers supportNodeList.forEachdirectly, butArray.from()helps with older ones). - Event Binding: Instead of
.click(), we useaddEventListener(). This lets you attach multiple listeners to the same element without overwriting existing ones—something jQuery does too, but it's good to see the native way. - Class Manipulation: jQuery's
.addClass()/.removeClass()maps directly to vanilla JS'sclassList.add()/classList.remove()—super straightforward once you get used to calling it on the DOM element itself. - DOM Traversal: jQuery's
.parent()/.siblings()are handy shortcuts, but in vanilla JS we useparentElementand loop through the parent's children to target siblings. It's a bit more verbose, but it gives you clear control over what elements you're targeting. - Animation: jQuery's
.fadeIn()is a pre-built method, but we used CSS transitions onopacityto mimic the effect here. CSS animations are more performant than JS-based ones, so this is a good practice to adopt. - DOM Ready: Instead of a
setTimeout(which is unreliable), we useDOMContentLoadedto ensure our code runs only after the DOM is fully parsed—this is the vanilla equivalent of jQuery's$(document).ready().
Tips for Your Vanilla JS Journey
- Start Tiny: Rewrite small jQuery snippets (like hiding an element on click) first. This builds muscle memory fast.
- Learn the DOM API: Get comfortable with methods like
closest()(great for traversing up the DOM, just like jQuery's.closest()),getAttribute, andclassList—they're your new best friends. - Lean on CSS: Use CSS for animations, hover states, and layout whenever possible. It's cleaner and faster than doing it all in JS.
- Check Browser Support: If you need to support older browsers, you might need polyfills for some methods, but modern browsers handle almost all vanilla JS features natively now.
内容的提问来源于stack exchange,提问作者leek1234
相关产品推荐
相关产品推荐

