当点击标签不起作用时,将 div 中的 HTML 图像源更改为 javascript

Change HTML image source in a div with javascript when click on label not working

我需要在单击标签时更改 div in HTML 中的图像。我认为我不需要为此使用 jquery,我只想使用 javascript。经过一些研究,它看起来很简单,所有的答案都是一样的,但我无法让它发挥作用。我知道单击标签时该功能有效,因为标签会改变颜色,但图像不会改变,我也没有收到任何语法错误。我正在使用 chrome。我不知道我做错了什么。

这是HTML/CSS代码:

<html>
<body>
  <div id="slc_on_label">
    <img src=https://ichef.bbci.co.uk/news/800/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg>
  </div>

  <style>
    #slc_on_label img {
      position:fixed;
      width:5.5%;
      left:10%;
      top:10%;
    }
  </style>

  <label class = "button" id="button" onclick="run(this)">0</label>

  <style>
  .button {background-color:Powderblue;
          font-size: 5vw;
        }
   </style>

  <script src="question.js" ></script>
</body>
</html>

这是 javascript 代码:

function run(button) {
  document.getElementById("slc_on_label").src="https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";
  button.style = "background-color:red";
}

您正试图在 <div id="slc_on_label"> 上设置 src 属性,而不是其中的 <img>

可以用document.querySelector()到select里面的图片div:

document.querySelector("#slc_on_label img").src =
    "https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";
function run(button) {
  document.querySelector('slc_on_label img').src =
    'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg';
  button.style.backgroundColor = 'red';
}

也没有破坏按钮样式。

<html>

<head>
    <style>
        #slc_on_label img {
            position: fixed;
            width: 5.5%;
            left: 10%;
            top: 10%;
        }

        .button {
            background-color: Powderblue;
            font-size: 5vw;
        }
    </style>
</head>

<body>
    <div id="slc_on_label">
        <img src="https://ichef.bbci.co.uk/news/800/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg">
    </div>

    <label class="button" id="button" onclick="run(this)">0</label>

    <script>
        function run(button) {
            document.querySelector("#slc_on_label img").setAttribute('src', 'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg');
            button.style = "background-color:red";
        };
    </script>
</body>

</html>