我想点击图片并将其更改为另一张图片,但它无法正常工作, 我使用了w3schools.com的代码,但它不会工作
这是代码:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="img/checkoff.png">
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "checkoff.png";
} else {
image.src = "checkon.png";
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
您的代码中存在问题
这里你只使用带有扩展名的图像文件的名称,你还需要提供图像的相对文件路径:像这样
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
您可以在此处查看此示例。
工作顺利。
希望这会对你有所帮助
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("generic-image-placeholder")) {
image.src = "https://cdn.noths-static.com/system/product_images/images/001/037/649/original_set-of-eight-white-heart-name-place-holders.jpg";
} else {
image.src = "https://www.webpagefx.com/blog/images/cdn.designinstruct.com/files/582-how-to-image-placeholders/generic-image-placeholder.png";
}
}
&#13;
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="https://cdn.noths-static.com/system/product_images/images/001/037/649/original_set-of-eight-white-heart-name-place-holders.jpg">
</body>
</html>
&#13;
答案 1 :(得分:0)
尝试以下代码正常运行
<img id="myImage" onclick="changeImage()" src="http://fakeimg.pl/300/">
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("http://fakeimg.pl/250x100/")) {
image.src = "http://fakeimg.pl/300/";
} else {
image.src = "http://fakeimg.pl/250x100/";
}
}
</script>
Click Here to see jsFiddle Demo
您的代码请在点击图片时更改路径
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon.png")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
</script>
答案 2 :(得分:-2)
代码中的图片路径不正确。请更新如下:
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
</script>