亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

單擊標簽不起作用時使用 javascript 更改 div 中的 HTML 圖像源

單擊標簽不起作用時使用 javascript 更改 div 中的 HTML 圖像源

慕無忌1623718 2023-03-24 17:13:19
單擊標簽時,我需要更改 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";}
查看完整描述

3 回答

?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

您正在嘗試將src屬性設置為 on<div id="slc_on_label">而不是在<img>其內部。

您可以使用document.querySelector()選擇里面的圖像div

document.querySelector("#slc_on_label img").src = 
   "https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";


查看完整回答
反對 回復 2023-03-24
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

<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>


查看完整回答
反對 回復 2023-03-24
?
DIEA

TA貢獻1820條經驗 獲得超2個贊

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';

}

也不破壞按鈕樣式。


查看完整回答
反對 回復 2023-03-24
  • 3 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號