document.getElementsByClassName("HeartSpanImage")[0].addEventListener("click", function() {
if (this.classList.contains("active")) {
this.classList.remove("active");
} else this.classList.add("active");
}) body{
display: flex;
justify-content: center;
}
.cardOfFavorite{
position: relative;
}
.HeartSpanImage{
margin-right: 5px;
padding: 10px 0;
font-size: 35px;
color: grey;
}
.HeartSpanImage:active{
transform: scale(0.9);
}
.HeartSpanImage.active{
color: red;
}
.HeartSpanImage:focus> .imageHide{
display: block;
}
.HeartSpanImage:hover, .HeartSpanImage:focus{
color: red;
transform: scale(1.1);
}<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="containerOfFavorite">
<div class="cardOfFavorite" style="border: 5px solid red; width:250px; display:flex;
flex-direction:column; justify-content:center; align-items: center;
padding: 7px; position: relative; cursor: pointer;">
<span class="material-icons HeartSpanImage active delete-itemFavorite" id="HeartSpanImage" data-name="name" data-price="1.50"> favorite </span>
<img class="amico" src="https://www.corsair.com/de/de/medias/sys_master/images/images/h1d/he3/9950073159710/CS-9020031-PE/Gallery/CORSAIR_ONE_i300_2022_01/-CS-9020031-PE-Gallery-CORSAIR-ONE-i300-2022-01.png_515Wx515H" alt="" width="150px">
<img src="" class="imageHide" id="imageHide"></img>
<h3 style="color: red;">Title</h3>
<label style="color:grey;" for="">$1.50</label>
</div>
</body>
我有一个关于“添加到收藏夹”按钮的问题,以前你们中有人为这个按钮设计了javascript代码吗?我想设计这个按钮,让1-当你点击按钮,产品被添加到收藏列表2-当你再次点击按钮,该项目从收藏列表中删除,这两个功能如何与一个按钮工作?
发布于 2022-08-20 11:22:19
您已经得到了您的if语句,检查/存储最喜爱的状态(心脏)。用那个。
据我所知,你在你最喜欢的图标上有数据-*属性。我还会添加一个特定于该产品的唯一data-id,因为使用name有时会造成某些问题。
您可以通过dataset属性获取数据-*属性,如下面的示例所示。
document.getElementsByClassName("HeartSpanImage")[0].addEventListener("click", function() {
let name = this.dataset.name;
let price = this.dataset.price;
if (this.classList.contains("active")) {
this.classList.remove("active");
addToFavorites(name, price);
} else {
this.classList.add("active");
removeFromFavorites(name, price);
}
})addToFavorites()和removeFromFavorites()是由你决定的。您还没有编写任何关于如何存储它的信息,让它将其发送到服务器以通过localStorage保存在用户的磁盘上。
https://stackoverflow.com/questions/73417692
复制相似问题