html js怎么实现点击一个图标变色,比如说图标是❤,点击之后变成红心。

在线等!html怎么点击一个图标变色,比如说图标是❤,点击之后变成红心。需要详细说明。
需要js详细过程,图标是用css控制的(background-image),没有详细过程不要来!谢谢

这个再编程中,很常见,也有很多种写法,介绍两种。
1.图标用img标签显示,再img标签点击后,更改img的src属性,改变图标,将原来的空心换成红心的图片。
2.图标用css控制,设置background-image显示空心的背景图片,这里图片最好是png的,点击后换成红心的图片。

无论哪种,注意记录用户的点击行为,下次进去后直接显示红心的图标。比如百度app的点赞,要记录用户再哪个帖子点赞了,下次该用户再查看这个帖子的时候,默认显示点赞后的图标。追问

?我想问的是怎么点击之后换成红心,可以详细说明吗,谢谢

追答

前面都说了啊,第一种情况,设置img的src属性为新图片的url地址。第二种是设置图片的background-image属性为新图片的url地址。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-05-01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
  
</head>
<body>
<img id="kongxin" src="images/kongxin.png" alt="" />
<img id="shixin" src="images/shixin.png" alt="" />
</body>

<!-- 先隐藏实心  可以理解为  kongxin  是一个颜色   shixin  是一个颜色-->
<style type="text/css">
  #shixin{
    display:none;
  }
</style>

<script type="text/javascript">
  var kongxin = document.getElementById("kongxin");
  var shixin = document.getElementById("shixin");
  kongxin.onclick=function(){
    this.style.display = 'none';
    shixin.style.display = 'block';
    
  }
</script>
</html>

追问

点击是实心,再点击不能变回空心,这个怎么解决呢?谢谢

追答<script type="text/javascript">
  var kongxin = document.getElementById("kongxin");
  var shixin = document.getElementById("shixin");
  
  //空心点击变实心
  kongxin.onclick=function(){
    this.style.display = 'none';
    shixin.style.display = 'block';
     
  }
  //实心点击变空心
  shixin.onclick=function(){
    this.style.display = 'none';
    kongxin.style.display = 'block';
     
  }
</script>

本回答被提问者采纳
第2个回答  2019-05-01
百度Js控制CSS,随便点开一个博客,你照着做就是。内容太多,我手机打字得给你打到明天,
document.getElementById("xx").style.xxx,这个是核心代码。
相似回答