我計劃向我的網站博客添加過濾功能。為此,每篇博文都將與一個關鍵字相關聯。選擇這些關鍵字將顯示/過濾與該特定關鍵字類別相關聯的所有博客。
在下面的代碼中,我將我的博客分為 3 個類別(森林、鳥類和海洋)。但是,我也希望一些博客與多個關鍵字(兩個或三個)相關聯,請參閱下面片段中的“森林鳥類”部分。如果有人可以幫助我如何做,那就太好了。
代碼也可以在這里參考:https : //jsfiddle.net/chandrakant98c/e5u08d1q/1/#&togetherjs=l4Kte0VJDV
顯示代碼片段
<!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">
<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>
<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>
uj5u.com熱心網友回復:
以下是您可以更改的內容,在第 198 行:
<div class="column Birds">
您訂購的“森林鳥類”僅作為“鳥類”。將第 198 行更改為此應該可以解決此問題:
<div class="column Birds Forest">
uj5u.com熱心網友回復:
我強烈不鼓勵你使用className來改變類名,在這種情況下我會使用classList。
至于你如何做補充,將有說兩個影像最初的問題鳥在林同時使用鳥 按鈕和森林 按鈕通過添加,這可以實作類兩種鳥和森林到,將有兩個影像鳥和森林 風光--> <div >. 然后例如當您使用條件檢查列節點串列時,如果列類串列包含->columns.classList.contains('birds') 然后添加類show -->columns.classList.add('show') 它將顯示該列。
不過,您確實不需要所有那些復雜的函式和代碼。我建議在你的 HTML 中添加一個JS eventHandler而不是onclick事件。這將允許您通過單個函式運行所有代碼并直接處理事件。只需要幾個條件來處理按鈕 活動和列 顯示。
看看下面的重構代碼,我在代碼片段中添加了詳細的注釋以進一步幫助解釋。
如果您對任何事情有任何疑問,請告訴我。
注意:在條件上......我在解釋中使用了三元條件,這些與常規條件相同,它們只是簡寫版本。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401776.html
標籤:javascript html css 嵌入
