当单击标签不工作时,使用javascript更改div中的HTML图像源
单击标签时,我需要更改HTML中div内的图像。我不认为我需要使用jquery,我只想使用javascript。经过一些研究,它看起来很简单,所有的答案都是一样的,但我无法让它发挥作用。我知道当点击标签时这个函数是有效的,因为标签会改变颜色,但是图像不会改变,我也不会得到任何语法错误。我用的是chrome。我不知道我做错了什么 这是HTML/CSS代码:当单击标签不工作时,使用javascript更改div中的HTML图像源,javascript,html,css,image,src,Javascript,Html,Css,Image,Src,单击标签时,我需要更改HTML中div内的图像。我不认为我需要使用jquery,我只想使用javascript。经过一些研究,它看起来很简单,所有的答案都是一样的,但我无法让它发挥作用。我知道当点击标签时这个函数是有效的,因为标签会改变颜色,但是图像不会改变,我也不会得到任何语法错误。我用的是chrome。我不知道我做错了什么 这是HTML/CSS代码: <html> <body> <div id="slc_on_label">
<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>
您试图在
上设置src
属性,而不是其中的
您可以使用document.querySelector()
选择div中的图像
:
也不会破坏按钮样式。
#标签上的slc\U img{
位置:固定;
宽度:5.5%;
左:10%;
排名前10%;
}
.按钮{
背景色:粉蓝色;
字体大小:5vw;
}
0
功能运行(按钮){
document.querySelector(“#slc_on#u label img”).setAttribute('src','https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg');
button.style=“背景色:红色”;
};
您需要将id slc\u放在图像上的标签上,而不是放在div上。您正在尝试更改div的src吗?div没有来源。这是真的!谢谢@Talmacel Marian Silviu按照您编写代码的方式,您正在尝试更改div的src。要解决此问题,请使用您已经使用document.querySelector编写的相同选择器(“标签img上的slc#u”)正确查找元素img。现在,选择正确的元素后,您可以更改src值。
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";
}
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';
}