You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现每3个元素的Show More/Show Less切换功能

实现分段显示/隐藏.content下的.items元素

Hey there! Let's fix this up for you. The issue with the previous jQuery solution you found is probably that it was built for a different structure or didn't handle multiple .content containers properly. I'll walk you through a tailored solution that fits your exact HTML setup, with both jQuery and vanilla JS options.

Step 1: Update Your HTML

First, we need to add a toggle button inside each .content container—this will let users trigger the show more/less action:

<div class="content">
  <div class="items">1</div>
  <div class="items">2</div>
  <div class="items">3</div>
  <div class="items">4</div>
  <div class="items">5</div>
  <div class="items">6</div>
  <div class="items">7</div>
  <!-- Add this toggle button -->
  <button class="toggle-btn">SHOW MORE</button>
</div>

Step 2: Basic CSS Setup

We'll start by hiding all items beyond the first 3 by default, and style the button a bit:

/* Hide all items starting from the 4th one */
.content .items:nth-child(n+4) {
  display: none;
}

/* Optional: Style the toggle button to fit your design */
.toggle-btn {
  margin-top: 12px;
  padding: 8px 18px;
  border: 1px solid #ccc;
  background: #f5f5f5;
  cursor: pointer;
  border-radius: 4px;
}

.toggle-btn:hover {
  background: #eee;
}

Step 3: jQuery Implementation (Since you referenced jQuery)

This code will handle the toggle logic, and it works for multiple .content containers on the same page without conflicts:

$(document).ready(function() {
  // Loop through each .content container individually
  $('.content').each(function() {
    const $content = $(this);
    const $allItems = $content.find('.items');
    const totalItems = $allItems.length;
    const $toggleBtn = $content.find('.toggle-btn');
    let currentlyVisible = 3; // Start with 3 visible items

    // Hide the button if there are 3 or fewer items total
    if (totalItems <= 3) {
      $toggleBtn.hide();
      return;
    }

    $toggleBtn.on('click', function() {
      if ($toggleBtn.text() === 'SHOW MORE') {
        // Calculate how many more items to show (max 3, don't exceed total)
        const nextVisibleCount = Math.min(currentlyVisible + 3, totalItems);
        // Show the next batch of items
        $allItems.slice(currentlyVisible, nextVisibleCount).show();
        currentlyVisible = nextVisibleCount;

        // Switch button text to "SHOW LESS" if all items are visible
        if (currentlyVisible === totalItems) {
          $toggleBtn.text('SHOW LESS');
        }
      } else {
        // Hide all items beyond the first 3
        $allItems.slice(3).hide();
        currentlyVisible = 3;
        $toggleBtn.text('SHOW MORE');
      }
    });
  });
});

Key Details About This jQuery Code:

  • It targets each .content container separately, so if you have multiple on your page, they won't interfere with each other.
  • It handles edge cases: if there are 3 or fewer items, the button is hidden entirely (no need for it!).
  • It uses slice() to target specific ranges of items, which is clean and efficient.
  • It updates the button text dynamically based on the current state.

Step 4: Vanilla JavaScript Alternative (No jQuery Needed)

If you don't want to rely on jQuery, here's a native JS version that does the exact same thing:

document.addEventListener('DOMContentLoaded', function() {
  // Get all .content containers
  const contentContainers = document.querySelectorAll('.content');

  contentContainers.forEach(container => {
    const allItems = container.querySelectorAll('.items');
    const totalItems = allItems.length;
    const toggleBtn = container.querySelector('.toggle-btn');
    let currentlyVisible = 3;

    // Hide button if there's no need for it
    if (totalItems <= 3) {
      toggleBtn.style.display = 'none';
      return;
    }

    toggleBtn.addEventListener('click', function() {
      if (toggleBtn.textContent === 'SHOW MORE') {
        const nextVisibleCount = Math.min(currentlyVisible + 3, totalItems);
        // Show the next batch of items
        for (let i = currentlyVisible; i < nextVisibleCount; i++) {
          // Use the display value your .items use by default (e.g., 'flex' if they're flex items)
          allItems[i].style.display = 'block';
        }
        currentlyVisible = nextVisibleCount;

        if (currentlyVisible === totalItems) {
          toggleBtn.textContent = 'SHOW LESS';
        }
      } else {
        // Hide items beyond the first 3
        for (let i = 3; i < totalItems; i++) {
          allItems[i].style.display = 'none';
        }
        currentlyVisible = 3;
        toggleBtn.textContent = 'SHOW MORE';
      }
    });
  });
});

Quick Note for Vanilla JS:

If your .items elements use a display value other than block (like flex or grid), make sure to update the style.display value in the code to match your default layout.

Final Tips

  • You can adjust the number of items shown per "SHOW MORE" click by changing the 3 in the code to any number you want.
  • Feel free to tweak the CSS to make the button match your site's design—colors, padding, font, etc.
  • Test with different numbers of items to make sure edge cases (like exactly 3 items, exactly 6 items) work as expected.

内容的提问来源于stack exchange,提问作者siwakorn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:20:33