图片自适应大小是一种常见的需求,尤其是在响应式网页设计中。以下是一个通用的JavaScript代码示例,用于使图片根据其容器的大小自动调整尺寸:
以下是一个简单的JavaScript函数,用于使图片根据其容器的宽度自适应大小:
function resizeImages() {
var images = document.querySelectorAll('img.responsive');
images.forEach(function(img) {
var container = img.parentElement;
if (container) {
img.style.width = '100%';
img.style.height = 'auto';
}
});
}
// 初始调用
resizeImages();
// 监听窗口大小变化,重新调整图片大小
window.addEventListener('resize', resizeImages);document.querySelectorAll('img.responsive')选择所有带有responsive类的图片。height: auto确保图片按比例缩放,避免变形。srcset和sizes属性)来提供不同分辨率的图片。通过以上方法,可以有效地实现图片的自适应大小,提升网页的用户体验和性能。
没有搜到相关的文章