javascript - 单击标签不起作用时,使用 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";
}
解决方案
您正在尝试将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";
推荐阅读
- bash - 输入中的转义括号
- c# - 在 .NET Core 2.2 中使用 xsltc.exe 生成程序集?
- python-3.x - 访问每个href链接后webscrape返回空字符串
- python - 我如何在熊猫中矢量化这个操作?
- python - Django CreateView 直观地指示必填字段,无需自定义模板
- batch-file - 如何在“for”命令中循环命令?
- node.js - Node.js 无法访问 Google AdSense 管理 API。'用户没有 AdSense 帐户'
- excel - 如何将工作表用作函数?
- google-apps-script - 不一致的错误消息“不允许操作(第 298 行,文件”
")" - ios - 在模拟器上运行,同时拥有在模拟器上不显示类的 SDK(阻止我运行)