练习1_DOM点赞.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <link rel="stylesheet" href="https://at.alicdn.com/t/c/font_4974983_z46pr7nyg5p.css">
  8. <style>
  9. body{
  10. background-color: #f9f9f9;
  11. }
  12. .like-box{
  13. width: 200px;
  14. height: 200px;
  15. border-color: #fff;
  16. box-shadow: 0 0 10px rgba(0,0,0,0.5);
  17. position: fixed;
  18. top:50%;
  19. left: 50%;
  20. margin-top: -160px;
  21. margin-left: -140px;
  22. padding: 60px 40px;
  23. text-align: center;
  24. }
  25. .like-box .like-title{
  26. font-size: 20px;
  27. font-weight: bold;
  28. margin-bottom: 20px;
  29. }
  30. .like-box .like-icon .iconfont{
  31. font-size: 70px;
  32. color: #aaa;
  33. }
  34. .like-box .like-icon .iconfont:hover{
  35. color: red;
  36. cursor: pointer;
  37. }
  38. .like-box .like-num{
  39. font-size: 30px;
  40. font-weight: bold;
  41. }
  42. .like-box .like-text{
  43. margin-top: 10px;
  44. font-size: 12px;
  45. color: #aaa;
  46. }
  47. </style>
  48. </head>
  49. <body>
  50. <div class="like-box">
  51. <div class="like-title">点赞计数器</div>
  52. <div class="like-icon">
  53. <i class="iconfont icon-icons-"></i>
  54. </div>
  55. <div class="like-num"></div>
  56. <div class="like-text">点击心形图标进行点赞</div>
  57. </div>
  58. <script>
  59. // 功能一 实现向标签内插入数组
  60. // 获取数字标签 返回类数组
  61. var likeIcon = document.getElementsByClassName("like-num");
  62. // 从类数组中取出数字标签
  63. likeIcon = likeIcon[0];
  64. // 向数字标签中写入内容
  65. likeIcon.innerText = 0;
  66. // 功能二实现累加
  67. // 获取心形图标
  68. var likeBtn = document.getElementsByClassName("iconfont");
  69. // 从数组中取出心形图标
  70. likeBtn = likeBtn[0];
  71. // 给心形图标添加点击事件
  72. // 定义变量用作于累计的数字
  73. var num = 0;
  74. likeBtn.onclick = function(){
  75. // 让num进行一个累加操作
  76. num++;
  77. // 把累加后的数字赋值给数字标签
  78. likeIcon.innerText = num;
  79. }
  80. </script>
  81. </body>
  82. </html>