HTML DOM 改变image的src
2025-04-24
13
参考资料
HTML DOM 改变 image 的 src
基本介绍
通过 JavaScript 可以动态修改 HTML 中 <img> 元素的 src 属性,实现图片切换效果。
相关标签
<img>- 用于在网页中嵌入图像<button>- 常用于触发图片切换的交互元素
基本用法
document.getElementById("myImage").src = "newImage.jpg";完整实例
<!DOCTYPE html>
<html>
<head>
<title>Image Source Change</title>
<style>
#imageContainer {
width: 500px;
height: 300px;
border: 1px solid #ccc;
margin-bottom: 10px;
}
#myImage {
width: 100%;
height: 100%;
object-fit: cover;
}
.btn {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin-right: 10px;
}
.btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="imageContainer">
<img id="myImage" src="image1.jpg" alt="Sample Image">
</div>
<button class="btn" onclick="changeImage('image1.jpg')">Image 1</button>
<button class="btn" onclick="changeImage('image2.jpg')">Image 2</button>
<button class="btn" onclick="changeImage('image3.jpg')">Image 3</button>
<script>
function changeImage(newSrc) {
document.getElementById("myImage").src = newSrc;
}
</script>
</body>
</html>功能扩展
预加载图片:
function preloadImage(url) {
const img = new Image();
img.src = url;
}
// 预加载所有图片
preloadImage("image2.jpg");
preloadImage("image3.jpg");CSS 过渡效果:
#myImage {
transition: opacity 0.5s ease-in-out;
}
.fade-out {
opacity: 0;
}function changeImageWithFade(newSrc) {
const img = document.getElementById("myImage");
img.classList.add("fade-out");
setTimeout(() => {
img.src = newSrc;
img.classList.remove("fade-out");
}, 500);
}响应式图片切换:
function responsiveImageChange() {
const screenWidth = window.innerWidth;
const img = document.getElementById("myImage");
if (screenWidth < 768) {
img.src = "mobile-image.jpg";
} else {
img.src = "desktop-image.jpg";
}
}
// 监听窗口大小变化
window.addEventListener("resize", responsiveImageChange);懒加载实现:
<img id="myImage" data-src="image-to-lazy-load.jpg" src="placeholder.jpg" alt="Lazy Load Image">
<script>
document.addEventListener("DOMContentLoaded", function() {
const lazyImage = document.getElementById("myImage");
// 当图片进入视口时加载
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
lazyImage.src = lazyImage.dataset.src;
observer.unobserve(lazyImage);
}
});
});
observer.observe(lazyImage);
});
</script>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-1706.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
