单击标签不起作用时使用 javascript 更改 div 中的 HTML 图像源

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


这是 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";

}


慕无忌1623718
浏览 149回答 3
3回答

一只斗牛犬

您正在尝试将src属性设置为 on<div id="slc_on_label">而不是在<img>其内部。您可以使用document.querySelector()选择里面的图像div:document.querySelector("#slc_on_label&nbsp;img").src&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;"https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";

慕田峪4524236

<html><head>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; #slc_on_label img {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; position: fixed;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width: 5.5%;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left: 10%;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; top: 10%;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; .button {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; background-color: Powderblue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; font-size: 5vw;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style></head><body>&nbsp; &nbsp; <div id="slc_on_label">&nbsp; &nbsp; &nbsp; &nbsp; <img src="https://ichef.bbci.co.uk/news/800/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg">&nbsp; &nbsp; </div>&nbsp; &nbsp; <label class="button" id="button" onclick="run(this)">0</label>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function run(button) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.querySelector("#slc_on_label img").setAttribute('src', 'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; button.style = "background-color:red";&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; </script></body></html>

DIEA

function run(button) {&nbsp; document.querySelector('slc_on_label img').src =&nbsp; &nbsp; 'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg';&nbsp; button.style.backgroundColor = 'red';}也不破坏按钮样式。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript