修改元素属性

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

修改图片属性

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      img {
        width: 300px;
      }
    </style>
  </head>

  <body>
    <button id="ldh">刘德华</button>
    <button id="zxy">张学友</button> <br />
    <img src="images/ldh.jpg" alt="" title="刘德华" />

    <script>
      // 修改元素属性 src

      // 1. 获取元素
      var ldh = document.getElementById("ldh");
      var zxy = document.getElementById("zxy");
      var img = document.querySelector("img");

      // 2. 注册事件  处理程序
      zxy.onclick = function () {
        img.src = "images/zxy.jpg";
        img.title = "张学友思密达";
      };

      ldh.onclick = function () {
        img.src = "images/ldh.jpg";
        img.title = "刘德华";
      };
    </script>
  </body>
</html>