0
if (document.getElementById) {

function alterImg() {
    document.body.getElementById('sendimg').src="url('images/tridown.png')";
}

}

然后是html:

<div id="sendbutton">
<img id="sendimg" src="images/tri.png" onclick="alterImg()" />
</div>

我也尝试使用 this 关键字引用,但无济于事。

4

5 回答 5

2

您的代码存在三个问题:

  • 您使用的文档.body .getElementById。" getElementById" 是 的方法,而document不是 body 元素。
  • 您正在将 css 与 html 混合。在 html 中,您将 url 分配给src图像的属性。在 css 中,您用于url(...)引用图像,例如用于背景。
  • 您在 if 语句中使用函数声明。请注意,这确实在当前范围内声明了函数(我假设是全局的),无论 if 块是否被执行。如果只想在document.getElementById可用时定义函数,则需要使用
if (document.getElementById) {
    var alterImg = function () {
        document.getElementById('sendimg').src="images/tridown.png";
    }
} 
于 2012-05-17T23:35:15.580 回答
1

文档。正文.getElementById

于 2012-05-17T23:27:09.847 回答
0

这里有几个问题:

  1. src 属性不需要包裹在 url() 周围
  2. 使用document.getElementById而不是document.body.getElementById

    函数 alterImg() { document.getElementById('sendimg').src = "images/tridown.png"; }

于 2012-05-17T23:34:09.403 回答
0

从 .src="url('images/tridown.png')" 中删除 url('') 语句

以下对我有用:

<div id="sendbutton">
<img id="sendimg" src="http://placehold.it/64x64" onclick="alterImg()" />
</div>


<script type="text/javascript">
    if (document.getElementById) {

function alterImg() {
    document.body.getElementById('sendimg').src="http://placehold.it/128x128";
}

}

</script>
​
于 2012-05-17T23:34:55.587 回答
0

getElementById方法仅在document对象上定义,而不是在document.body. 此外,该src属性不是 CSS 属性,因此不能url(...)用作值。你应该简单地写:

document.getElementById('sendimg').src = images/tridown.png";

有关 的更完整描述HTMLImageElement,请查看Mozilla 开发者网络

于 2012-05-17T23:35:31.307 回答