将多个过滤关键字添加到图库中的单个博客?

Add multiple filtering keywords to a single blog in a gallery?

我打算在我的网站博客中添加过滤功能。为此,每个博客 post 将与一个关键字相关联。选择这些关键字将 show/filter 所有与该特定关键字类别关联的博客。

在下面的代码中,我将我的博客分为 3 类(森林、鸟类和海洋)。但是,我还希望某些博客与多个关键字(两个或三个)相关联,请参阅下面代码段中的 'Forest Birds' 部分。如果有人可以帮助我如何做,那就太好了。

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
    /* Wildcard styling */
    
    * {
      box-sizing: border-box;
    }
    /* Padding for whole body */
    
    body {
      padding: 1px;
    }
    
    .container {
      max-width: 1200px;
      margin: auto;
    }
    /* Styling h2 tag */
    
    h1 {
      Color: green;
      word-break: break-all;
    }
    /* Anchor tag decoration */
    
    a {
      text-decoration: none;
      color: #5673C8;
    }
    
    a:hover {
      color: lightblue;
    }
    
    .row {
      margin: 0px -14px;
      padding: 8px;
    }
    
    .row>.column {
      padding: 6px;
    }
    
    .column {
      float: left;
      width: 33%;
      display: none;
    }
    /* Content decoration */
    
    .content {
      background-color: white;
      padding: 10px;
      border: 1px solid gray;
    }
    /* Paragraph decoration */
    
    p {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 40;
      overflow: hidden;
    }
    
    .row:after {
      content: "";
      display: table;
      clear: both;
    }
    
    .content {
      background-color: white;
      padding: 10px;
      border: 1px solid gray;
    }
    
    .show {
      display: block;
    }
    /* Style the filter buttons */
    
    .bttn {
      border: none;
      padding: 8px 14px;
      background-color: gray;
    }
    
    .bttn:hover {
      background-color: #007EE5;
      opacity: 0.8;
    }
    
    .bttn.active {
      background-color: #007EE5;
      color: white;
    }
    /* Window size 850 width set */
    
    @media screen and (max-width: 850px) {
      .column {
        width: 50%;
      }
    }
    /* Window size 400 width set */
    
    @media screen and (max-width: 400px) {
      .column {
        width: 100%;
      }
    }
  </style>
</head>

<body>

  <!-- Title and tag -->
  <div class="container">

    <!-- button foreach group -->
    <div id="filtering">
      <button class="bttn active" onclick="geeksportal('all')">
            Show all
            </button>

      <button class="bttn" onclick="geeksportal('Forest')">
            Forest
            </button>

      <button class="bttn" onclick="geeksportal('Sea')">
            Sea
            </button>

      <button class="bttn" onclick="geeksportal('Birds')">
            Birds
            </button>
    </div>

    <!-- Portfolio Gallery Grid -->
    <div class="row">
      <div class="column Forest">
        <div class="content">
          <img src="https://learnenglishteens.britishcouncil.org/sites/teens/files/styles/article/public/field/image/rs930_135120665-low.jpg?itok=g5LI5W4C" alt="HTML" style="width:100%">
          <h3><a href="#">
                        Forest Wiki
                        </a>
          </h3>

          <p>
            A forest is an area of land dominated by trees.[1] Hundreds of definitions of forest are used throughout the world, incorporating factors such as tree density, tree height, land use, legal standing, and ecological function.[2][3][4] The United Nations'
            Food and Agriculture Organization (FAO) defines a forest as, "Land spanning more than 0.5 hectares with trees higher than 5 meters and a canopy cover of more than 10 percent, or trees able to reach these thresholds in situ. It does not include
            land that is predominantly under agricultural or urban use."[5] Using this definition, Global Forest Resources Assessment 2020 (FRA 2020) found that forests covered 4.06 billion hectares (10.0 billion acres; 40.6 million square kilometres;
            15.7 million square miles), or approximately 31 percent of the world's land area in 2020.
          </p>

        </div>
      </div>
      <div class="column Birds">
        <div class="content">
          <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMcwhEBBzhEUHD29jjdZswug7yXgje_WtbXA&usqp=CAU" alt="CSS" style="width:100%">
          <h3><a href="#">
                        Birds Wiki
                        </a>
          </h3>

          <p>
            Birds are a group of warm-blooded vertebrates constituting the class Aves /ˈeɪviːz/, characterised by feathers, toothless beaked jaws, the laying of hard-shelled eggs, a high metabolic rate, a four-chambered heart, and a strong yet lightweight skeleton.
            Birds live worldwide and range in size from the 5.5 cm (2.2 in) bee hummingbird to the 2.8 m (9 ft 2 in) ostrich. There are about ten thousand living species, more than half of which are passerine, or "perching" birds. Birds have wings whose
            development varies according to species; the only known groups without wings are the extinct moa and elephant birds. Wings, which evolved from forelimbs, gave birds the ability to fly, although further evolution has led to the loss of flight
            in some birds, including ratites, penguins, and diverse endemic island species. The digestive and respiratory systems of birds are also uniquely adapted for flight. Some bird species of aquatic environments, particularly seabirds and some
            waterbirds, have further evolved for swimming.
          </p>

        </div>
      </div>
      <div class="column Sea">
        <div class="content">
          <img src="https://climate.nasa.gov/system/news_items/main_images/2990_9827327865_98e0f0dc2d_o.jpg" alt="" style="width:100%">
          <h3><a href="#">
                        Sea Wiki
                        </a>
          </h3>

          <p>
            The sea, connected as the world ocean or simply the ocean, is the body of salty water that covers approximately 71 percent of the Earth's surface. The word sea is also used to denote second-order sections of the sea, such as the Mediterranean Sea, as
            well as certain large, entirely landlocked, saltwater lakes, such as the Caspian Sea.
          </p>

        </div>
      </div>
      <div class="column Birds Forest">
        <div class="content">
          <img src="https://c4.wallpaperflare.com/wallpaper/73/551/750/spring-rendezvous-forest-bird-green-wallpaper-preview.jpg" alt="" style="width:100%">
          <h3><a href="#">
                        Forest Birds
                        </a>
          </h3>

          <p>
            Types of forest birds are those that will be seen more often than not in tree lots and forested areas. When these bird species decide to travel in their spring or fall migrations, it is usually non-stop over open expanses until they can seek the cover
            of woodlots or larger forests, where they are the most comfortable with their surroundings. Once these different types of birds settle in their habitat, some will be found on the forest floor, others will be in the newer growths that are not
            high and again others will live in the higher areas of the trees right up into the canopies of the treetops. These birds will be a combination of seed eaters and insect eaters. As insect eaters, they manage the insect population and help the
            trees, by reducing the amount of insect damage being done to them. The seed-eating birds, as an example, the crossbills help the forest by opening the cones and letting seeds fall to the ground thereby giving them the opportunity to germinate
            in the soil and grow into young trees.


          </p>

        </div>
      </div>
      
      <div class="column Birds Sea">
        <div class="content">
          <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQssWko0aXJDv8qDfOwYE9xAfpn0nnV4ttugtHTSaRPtzAjDK4luY5bpwFspestoXv3QtM&usqp=CAU" alt="" style="width:100%">
          <h3><a href="#">
                        Sea Birds
                        </a>
          </h3>

          <p>
            Seabirds are birds that are adapted to life within the marine environment. While seabirds vary greatly in lifestyle, behaviour and physiology, they often exhibit striking convergent evolution, as the same environmental problems and feeding niches have resulted in similar adaptations.
          </p>

        </div>
      </div>
    
     
      <div class="column Forest Sea">
        <div class="content">
          <img src="https://cdnb.artstation.com/p/assets/images/images/003/051/837/large/sylvain-sarrailh-seaforestarstation.jpg?1469024090" alt="" style="width:100%">
          <h3><a href="#">
                        Forest Sea
                        </a>
          </h3>

          <p>
            Sea Forest is now cultivating more Asparagopsis than ever, and as our land and marine based farming operations continue to grow, so too will our positive impact on the planet.
          </p>

        </div>
      </div>
    </div>
  </div>

  <script>
    geeksportal("all")

    function geeksportal(c) {
      var x, i;

      x = document.getElementsByClassName("column");

      if (c == "all") c = "";

      for (i = 0; i < x.length; i++) {
        w3RemoveClass(x[i], "show");

        if (x[i].className.indexOf(c) > -1)
          w3AddClass(x[i], "show");
      }
    }

    function w3AddClass(element, name) {
      var i, arr1, arr2;
      arr1 = element.className.split(" ");
      arr2 = name.split(" ");

      for (i = 0; i < arr2.length; i++) {
        if (arr1.indexOf(arr2[i]) == -1) {
          element.className += " " + arr2[i];
        }
      }
    }

    function w3RemoveClass(element, name) {
      var i, arr1, arr2;
      arr1 = element.className.split(" ");
      arr2 = name.split(" ");
      for (i = 0; i < arr2.length; i++) {
        while (arr1.indexOf(arr2[i]) > -1) {
          arr1.splice(arr1.indexOf(arr2[i]), 1);
        }
      }
      element.className = arr1.join(" ");
    }

    // Add active class to the current
    // button (highlight it)
    var btnContainer = document.getElementById("filtering");
    var btns = btnContainer.getElementsByClassName("bttn");
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function() {

        var current =
          document.getElementsByClassName("active");

        current[0].className =
          current[0].className.replace(" active", "");

        this.className += " active";
      });
    }
  </script>
</body>

</html>
请全屏查看结果

以下是您可以在第 198 行更改的内容:

<div class="column Birds">

您订购的“森林鸟类”仅为“鸟类”。将第 198 行更改为此应该修复它:

<div class="column Birds Forest">
            

我强烈反对您使用 className 来更改 class 名称,我在这种情况下,将改为使用 classList

关于你最初的问题是如何添加一张图片,该图片会在 中同时显示 birds forest 同时使用 bird buttonforest button,这可以通过添加 class birdforest 到同时具有 birdsforest 的图像森林 风景 --> <div class="column birds forest show">。然后,例如,当您使用条件检查列 nodelist 时,如果 列 class 列表包含 -> columns.classList.contains('birds') 然后添加 class show --> columns.classList.add('show') 它会显示那一栏。

虽然你真的不需要所有那些复杂的函数和代码。我建议在 HTML 中添加 JS eventHandler 而不是 onclick 事件。这将允许您通过单个函数 运行 所有代码并直接处理事件。几个条件来处理 buttons activecolumns show就够了

看看下面的重构代码,我在代码片段中添加了详细的注释以进一步协助解释。

如果您有任何特别的问题,请告诉我。

注意: 关于条件...我在解释中使用了三元条件,它们与常规条件相同只是简写版本。

col.classList.contains(btnId) ? col.classList.add('show') : null 

相同
if(col.classList.contains(btnId)){
  col.classList.add('show')
}else{
  null
}

// intial query of the codument to get the buttons by their class selector
const button = document.querySelectorAll('.bttn');

// call back function to be used in the event handler within the 
// forEach function on the buttons node list we pass the event "e"
function showSections(e){

  // define a variable for the event.target.dataset.id set in the buttons html
  let btnId = e.target.dataset.id;
  
  // define a varaible for the column nodeList array
  let columns = document.querySelectorAll('.column');
  
  // run over the buttons nodeList and check/set the active class
  // we are using classList and NOT className, researching the difference 
  // of the two will be good on your end...
  button.forEach(btn => {
    // rather than checking each class, lets just remove active class then check
    btn.classList.remove('active');
    // conditional check if btn.dataset is the button pressed
    // if so, add the active class using btn.classList.add('active')
    btn.dataset.id === btnId ? btn.classList.add('active') : null
  })
  
  // run over the column nodeLists and check/set the show class
  // again we are using classList and NOT className...
  columns.forEach(col => {
    // again remove all iterations of show class
    col.classList.remove('show');
    // now check if the columns classList contains the dataset id 
    // from the button using e.target.dataset.id 
    col.classList.contains(btnId) ? col.classList.add('show') : null  
    btnId === 'all' ? col.classList.add('show') : null
  })
}

// forEach looping over the button node list
button.forEach(btn => {
  btn.addEventListener('click', showSections)
})
/* Wildcard styling */

* {
  box-sizing: border-box;
}


/* Padding for whole body */

body {
  padding: 1px;
}

.container {
  max-width: 1200px;
  margin: auto;
}


/* Styling h2 tag */

h1 {
  Color: green;
  word-break: break-all;
}


/* Anchor tag decoration */

a {
  text-decoration: none;
  color: #5673C8;
}

a:hover {
  color: lightblue;
}

.row {
  margin: 0px -14px;
  padding: 8px;
}

.row>.column {
  padding: 6px;
}

.column {
  float: left;
  width: 33%;
  display: none;
}


/* Content decoration */

.content {
  background-color: white;
  padding: 10px;
  border: 1px solid gray;
}


/* Paragraph decoration */

p {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 40;
  overflow: hidden;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.content {
  background-color: white;
  padding: 10px;
  border: 1px solid gray;
}

.show {
  display: block;
}


/* Style the filter buttons */

.bttn {
  border: none;
  padding: 8px 14px;
  background-color: gray;
}

.bttn:hover {
  background-color: #007EE5;
  opacity: 0.8;
}

.bttn.active {
  background-color: #007EE5;
  color: white;
}


/* Window size 850 width set */

@media screen and (max-width: 850px) {
  .column {
    width: 50%;
  }
}


/* Window size 400 width set */

@media screen and (max-width: 400px) {
  .column {
    width: 100%;
  }
}
<!-- Title and tag -->
<div class="container">

  <!-- button foreach group -->
  <div id="filtering">
  <!-- CHANGED - removed onclick attributes and added active class states 
       to the buttons directly, changes will be handled by JS event handlers
       within javascript functionand not in onlick attributes in HTML 
       Also added dataset id's for handling conditionals to change 
       like images -->
    <button data-id="all" class="bttn active">Show all</button>

    <button data-id="forest" class="bttn">Forest</button>

    <button data-id="sea" class="bttn">Sea</button>

    <button data-id="birds" class="bttn">Birds</button>
  </div>

  <!-- Portfolio Gallery Grid -->
  <div class="row">
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. for example this column has only forest, also changed the classes to
    lower clse to match the dataset id from the corresponding button  and added the 
    show class for initializing the first iteration of DOM loading -->
    <div class="column forest show">
      <div class="content">
        <img src="https://learnenglishteens.britishcouncil.org/sites/teens/files/styles/article/public/field/image/rs930_135120665-low.jpg?itok=g5LI5W4C" alt="HTML" style="width:100%">
        <h3>
          <a href="#">Forest Wiki</a>
        </h3>
        <p>A forest is an area of land dominated by trees.[1] Hundreds of definitions of forest are used throughout the world, incorporating factors such as tree density, tree height, land use, legal standing, and ecological function.[2][3][4] The United Nations' Food and Agriculture Organization (FAO) defines a forest as, "Land spanning more than 0.5 hectares with trees higher than 5 meters and a canopy cover of more than 10 percent, or trees able to reach these thresholds in situ. It does not include land that is predominantly under agricultural or urban use."[5] Using this definition, Global Forest Resources Assessment 2020 (FRA 2020) found that forests covered 4.06 billion hectares (10.0 billion acres; 40.6 million square kilometres; 15.7 million square miles), or approximately 31 percent of the world's land area in 2020.</p>
      </div>
    </div>
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. For example this column has only birds, also changed the classes to
    lower case to match the dataset id from the corresponding button and added the 
    show class for initializing the first iteration of DOM loading -->
    <div class="column birds show">
      <div class="content">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMcwhEBBzhEUHD29jjdZswug7yXgje_WtbXA&usqp=CAU" alt="CSS" style="width:100%">
        <h3>
          <a href="#">Birds Wiki</a>
        </h3>
        <p>Birds are a group of warm-blooded vertebrates constituting the class Aves /ˈeɪviːz/, characterised by feathers, toothless beaked jaws, the laying of hard-shelled eggs, a high metabolic rate, a four-chambered heart, and a strong yet lightweight skeleton. Birds live worldwide and range in size from the 5.5 cm (2.2 in) bee hummingbird to the 2.8 m (9 ft 2 in) ostrich. There are about ten thousand living species, more than half of which are passerine, or "perching" birds. Birds have wings whose development varies according to species; the only known groups without wings are the extinct moa and elephant birds. Wings, which evolved from forelimbs, gave birds the ability to fly, although further evolution has led to the loss of flight in some birds, including ratites, penguins, and diverse endemic island species. The digestive and respiratory systems of birds are also uniquely adapted for flight. Some bird species of aquatic environments, particularly seabirds and some waterbirds, have further evolved for swimming.</p>
      </div>
    </div>
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. For example this column has only sea, also changed the classes to
    lower case to match the dataset id from the corresponding button and added the 
    show class for initializing the first iteration of DOM loading -->
    <div class="column sea show">
      <div class="content">
        <img src="https://climate.nasa.gov/system/news_items/main_images/2990_9827327865_98e0f0dc2d_o.jpg" alt="" style="width:100%">
        <h3>
          <a href="#">Sea Wiki</a>
        </h3>
        <p>The sea, connected as the world ocean or simply the ocean, is the body of salty water that covers approximately 71 percent of the Earth's surface. The word sea is also used to denote second-order sections of the sea, such as the Mediterranean Sea, as well as certain large, entirely landlocked, saltwater lakes, such as the Caspian Sea.</p>
      </div>
    </div>
    <!-- CHANGED * Added classes the reflect the types of content contined with in 
    this column. For example this column has both birds and forest, also changed the 
    classes to lower case to match the dataset id from the corresponding button and 
    added the show class for initializing the first iteration of DOM loading -->
    <div class="column birds forest show">
      <div class="content">
        <img src="https://c4.wallpaperflare.com/wallpaper/73/551/750/spring-rendezvous-forest-bird-green-wallpaper-preview.jpg" alt="" style="width:100%">
        <h3>
          <a href="#">Forest Birds</a>
        </h3>
        <p>Types of forest birds are those that will be seen more often than not in tree lots and forested areas. When these bird species decide to travel in their spring or fall migrations, it is usually non-stop over open expanses until they can seek the cover of woodlots or larger forests, where they are the most comfortable with their surroundings. Once these different types of birds settle in their habitat, some will be found on the forest floor, others will be in the newer growths that are not high and again others will live in the higher areas of the trees right up into the canopies of the treetops. These birds will be a combination of seed eaters and insect eaters. As insect eaters, they manage the insect population and help the trees, by reducing the amount of insect damage being done to them. The seed-eating birds, as an example, the crossbills help the forest by opening the cones and letting seeds fall to the ground thereby giving them the opportunity to germinate in the soil and grow into young trees.</p>
      </div>
    </div>
  </div>
</div>