如何修正导航菜单逻辑:仅为上一个按钮添加previousButton类
Got it, let's fix this up for you! First, let's break down why your current code isn't behaving as you want:
prevAll()selects all previous sibling buttons instead of just the immediate one before the active button- You aren't clearing existing
previousandpreviousButtonclasses on subsequent clicks, which can leave stale styles on old elements
Here's the adjusted version that only adds previousButton to the direct previous button of the active one:
Modified JavaScript Code
// Set first button as active on page load $(".btn").first().addClass("active"); // Handle both click and focus events for better accessibility $(".btn").on("click focus", function(){ // Clear all active/previousButton classes from every button first $(".btn").removeClass("active previousButton"); // Mark the clicked/focused button as active $(this).addClass("active"); // Target ONLY the immediate preceding button and add the previousButton class $(this).prev(".btn").addClass("previousButton"); });
Updated CSS Code
We can remove the unnecessary .previous class since we don't need to style all prior buttons anymore:
.active { color: green; } .previousButton { color: pink; }
HTML Code (formatted for clarity)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="buttons"> <button class="btn">1. Page</button> <button class="btn">2. Page</button> <button class="btn">3. Page</button> <button class="btn">4. Page</button> <button class="btn">5. Page</button> </div>
Key Changes Explained:
- Clear all stale classes first: We wipe
activeandpreviousButtonfrom every button on each interaction to avoid leftover styles. - Use
prev()instead ofprevAll():prev()targets only the immediate preceding sibling that matches the selector—exactly the single "previous button" you need. - Combined event handler: Added both
clickandfocusevents to support both mouse and keyboard navigation, which is a nice touch for accessibility.
If you ever need to style all prior buttons later, you can reintroduce the .previous class and use prevAll(), but this solution directly addresses your request to target only the immediate previous button.
内容的提问来源于stack exchange,提问作者Zyonix
相关产品推荐
相关产品推荐

