这是我的代码,那么如何更改宽度属性呢?
<html>
<head>
<script type="text/javascript">
document.getElementById("cpul").src="hello.jpg";
</script>
</head>
<body>
<img src="hi.jpg" width="100" height="100" id="cpul">
</body>
</html>
以上是失败的,图像根本没有变化!!
但是为什么当我使用这段代码(从其他站点复制)时,图像发生了变化
<html>
<head>
<title>JS DD Function</title>
<script type="text/javascript">
function jsDropDown(imgid,folder,newimg)
{
document.getElementById(imgid).src="http://www.cookwithbetty.com/" + folder + "/" + newimg + ".gif";
}
</script>
</head>
<body>
<table>
<tr>
<td>
Foods: <select name="food" onChange="jsDropDown('cful','images',this.value)">
<option value="steak_icon">Steak</option>
<option value="salad_icon">Salad</option>
<option value="bread_icon">Bread</option>
</select><br />
</td>
<td>
<img src="http://www.cookwithbetty.com/images/steak_icon.gif" id="cful">
</body>
</html>
原文由 dramasea 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码不工作的最可能原因是它在元素存在于 DOM 之前执行。您应该将代码设置为在窗口
load
事件上运行,或将其放在文档末尾以确保在尝试访问该元素之前该元素存在。