JavaScript动态修改图片src属性的方法

作者:微光

时间:2026-10-29

浏览:304

本文介绍如何使用JavaScript动态修改图片的URL,即通过改变图片元素的src属性来显示新图片。示例代码展示了点击按钮触发changeSrc函数,将图片源从compman.gif切换为hackanm.gif,并指出新图片会继承原图的宽高属性。

文章目录

JavaScript动态修改图片src属性的方法

本文介绍一种利用JavaScript动态更改图片URL(src)的技术方案,供开发者参考。

通过修改图片元素的src属性,可以实现动态切换图片地址,从而在页面上展示新的图像内容。


<!DOCTYPE html>
<html>
<head>
<script>
function changeSrc()
{
document.getElementById("myImage").src="hackanm.gif";
}
</script>
</head>
<body>
<img id="myImage" src="compman.gif" width="107" height="98">
<br><br>
<input type="button" onclick="changeSrc()" value="Change image">
<p><b>Note:</b> The src property can be changed at any time. 
However, the new image inherits the height and width
attributes of the original image,
if not new height and width properties are specified.</p>
</body>
</html>

希望上述关于JavaScript程序设计的说明能对您的开发工作提供帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章