首页 > 解决方案 > 当我单击 vanilla javascript 中的其他按钮时,从所有其他按钮中删除 ACTIVE 类

问题描述

我想将“活动”分配给我单击的按钮,并在我这样做时从其他按钮中删除活动,我想在 Vanilla JS 中执行此操作,因为我想练习我的技能。我已经在 SO 上尝试过类似的问题,但是我无法让我的代码正常工作。

最终,我想为从我的数据库中获取的图像在 PHP 中创建一个画廊过滤器,我将其添加到我的代码中,如下所示,基于按钮,我想显示/隐藏类别。图像class = someCategoryimage_category我的数据库中的列接收。

帮助表示赞赏。

我试图考虑类似的问题。但我没能成功。

Vanilla JS 从除“活动”类之外的所有其他元素中删除类

HTML & PHP 代码:

     <div id="category-buttons">
    <h5>Choose image category</h5>
      <button id="All" class="catgory-button active" >All Categories</button>
      <button id="CNC_Machining_button" class="catgory-button">CNC_Machining</button>
      <button id="HP_Die_Casting" class="catgory-button">HP Die Casting</button>
      <button id="Iron_Casting" class="catgory-button">Iron Casting</button>
      <button id="Steel_Casting" class="catgory-button">Steel Casting</button>
      <button id="Precision_Casting" class="catgory-button">Precision Casting</button>
      <button id="Aluminium_Casting" class="catgory-button">Aluminum Casting</button>
    </div>


<section class="gallery-links">
<div class="wrapper">

  <h2 class="product-gallery-title">Product Gallery</h2>

  <div class="gallery-container">
    <?php
    include_once 'includes/dbh.inc.php';

    $sql = 'SELECT * FROM gallery ORDER BY orderGallery DESC';
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt,$sql)) {
      echo 'SQL statement failed!';
    } else {
      mysqli_stmt_execute($stmt);
      $result = mysqli_stmt_get_result($stmt);

      while ($row = mysqli_fetch_assoc($result)) {
        //what's echoed out by the database

        echo '  <a class="images '.$row["image_category"].'" style="background-repeat:no-repeat; background-image: url(gallery/'.$row["imgFullNameGallery"].')">
                <div class="color-overlay">
                <h3>'.$row["titleGallery"].'</h3>
                <p>'.$row["descGallery"].'</p>
                </div>
                </a>';
      }
    }


    ?>  

  </div>
 </div>

<?php

JS代码:

    let btns = Array.from(document.querySelectorAll('.category-button'));

    const handleClick = (e) => {
      e.preventDefault();
      btns.forEach(node => {
        node.classList.remove('active');
      });
      e.currentTarget.classList.add('active');
    }

    btns.forEach(node => {
      node.addEventListener('click', handleClick)
    });

相关CSS代码:

    #category-buttons {
    float: left;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    width: 12.5%;
    margin: 10vh 10px;
    }

    .category-button {
    padding: 20px;
    margin: 2px 0;;
    color: white;
    background: rgb(153, 124, 124);

    }

    .product-gallery-title {
    text-transform: uppercase;
    }

    .wrapper {
    text-align: center;
    width: 65%;
    margin: auto;
    }

    .gallery-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 13px;
    margin: auto;
    width: 100%;
    background: rgb(236, 236, 236);
    justify-content: center;
    }

    .images{
    height: 300px;
    width: 300px;
    max-width: 300px;
    max-height: 300px;
    text-decoration: none;
    }

预期结果: 单击时,按钮接收active类,范围内的其他按钮会丢失它们。

标签: javascriptcsshtml

解决方案


例如,您可以做的是将活动按钮存储在全局变量中,并在单击另一个按钮时使用该变量从中删除类。

所以是这样的:

let btns = Array.from(document.querySelectorAll('.category_btn'));
let activeButton = null;

// The button which would be used to add 'active' class to
// all the buttons.
let allButton = document.querySelector('#All');

const handleClick = (e) => {
  e.preventDefault();
  e.currentTarget.classList.add('active');
  // Checks that the activeButton is defined (initially it's null).
  // Also checks that the button that was clicked is not the button which is
  // already active to avoid removing the active class on double click.
  if (activeButton != null && activeButton != e.currentTarget) {
    activeButton.classList.remove('active');
  }
  activeButton = e.currentTarget;
}

btns.forEach(node => {
  node.addEventListener('click', handleClick)
});

// Listen to a click event from the "allButton" and when it's clicked,
// loop through the buttons array and add 'active' class to all buttons
// in it.
allButton.addEventListener('click', function() {
    btns.forEach(btn => {
        btn.classList.add('active');
    })
});

我目前没有任何地方可以测试和验证它是否有效,但我看不出它为什么不起作用。


推荐阅读