首页 > 解决方案 > 单击时更改颜色的链接,在重新加载页面时恢复

问题描述

我正在尝试创建将图标包装在标签中的样式。当您单击该图标时,它会改变颜色,因此您知道它已被单击。重新加载页面后,图标将恢复为未单击的原始颜色。这将用于具有数十/数百个图标的页面,例如表格;所以这就是为什么查看被点击的内容很重要的原因。

a {
  text-decoration: none;
}

.dog-icon:before {
  content: "\f6d3";
  font-family: 'Font Awesome 5 Free';
  font-size: 40px;
  font-weight: 900;
  padding: 40px;
}
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet"/>

  <div style="margin-top: 40px;">
    <a href="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=1200:*" target="_blank" class="dog-icon"></a>
    <a href="https://www.cdc.gov/healthypets/images/pets/angry-dog.jpg" target="_blank" class="dog-icon"></a>
    <a href="https://media.npr.org/assets/img/2021/04/27/prancer_wide-db59609b5bd96c9e56e4dfe32d198461197880c2.jpg?s=1400" target="_blank" class="dog-icon"></a>
    <a href="https://s3-us-west-2.amazonaws.com/uw-s3-cdn/wp-content/uploads/sites/6/2019/10/08113321/Dog-behavior-Kasper-Luijsterburg.jpg" target="_blank" class="dog-icon"></a>
    <a href="https://i.ytimg.com/vi/EVqxcWQOEnU/maxresdefault.jpg" target="_blank" class="dog-icon"></a>
  </div>

标签: javascripthtmljquerycss

解决方案


如果你添加一点 JavaScript 代码,它可以很容易地完成:

document.querySelector(".links").onclick=ev=>{if(ev.target.tagName=="A")
  ev.target.className="done"
}
.links a {
  text-decoration: none;
  font-family: 'Font Awesome 5 Free';
  font-size: 40px;
  font-weight: 900;
  margin: 20px;
}
.links a.done { color:green }
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet"/>

  <div class="links" style="margin-top: 40px;">
    <a href="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=1200:*" target="_blank">&#xf6d3;</a>
    <a href="https://www.cdc.gov/healthypets/images/pets/angry-dog.jpg" target="_blank">&#xf6d3;</a>
    <a href="https://media.npr.org/assets/img/2021/04/27/prancer_wide-db59609b5bd96c9e56e4dfe32d198461197880c2.jpg?s=1400" target="_blank">&#xf6d3;</a>
    <a href="https://s3-us-west-2.amazonaws.com/uw-s3-cdn/wp-content/uploads/sites/6/2019/10/08113321/Dog-behavior-Kasper-Luijsterburg.jpg" target="_blank">&#xf6d3;</a>
    <a href="https://i.ytimg.com/vi/EVqxcWQOEnU/maxresdefault.jpg" target="_blank">&#xf6d3;</a>
  </div>


推荐阅读