下面是纯js实现div内图片自适应大小的完整攻略:
下面是纯js实现div内图片自适应大小的完整攻略:
目录
- 实现思路
- 代码实现
- 示例一
- 示例二
实现思路
实现div内图片自适应大小,需要解决以下两个问题:
- 如何获取图片的宽度和高度?
- 如何在图片加载完成后将其按照正确的比例缩放到合适的大小?
因此,我们的实现思路是:
- 使用JS监听图片的
load
事件,在图片加载完成后获取其宽度和高度。 - 判断图片的宽高比例与容器的宽高比例,如果不同,则根据比例计算出适当的缩放大小,然后将缩放大小应用于图片。
代码实现
HTML结构示例:
<div class="container">
<img src="example.jpg" alt="example image">
</div>
CSS样式示例:
.container {
width: 500px;
height: 500px;
}
img {
max-width: 100%;
max-height: 100%;
}
JS代码:
// 获取所有包含图片的容器
const containers = document.querySelectorAll('.container');
// 遍历所有容器
containers.forEach(container => {
// 获取容器和图片对象
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const img = container.querySelector('img');
// 监听图片的load事件
img.addEventListener('load', () => {
// 获取图片的宽度和高度
const imgWidth = img.width;
const imgHeight = img.height;
// 判断图片宽高比例和容器宽高比例是否相同
const containerRatio = containerWidth / containerHeight;
const imgRatio = imgWidth / imgHeight;
if (containerRatio !== imgRatio) {
// 计算缩放比例
let scaleRatio;
if (imgRatio > containerRatio) {
// 宽度缩放
scaleRatio = containerWidth / imgWidth;
} else {
// 高度缩放
scaleRatio = containerHeight / imgHeight;
}
// 应用缩放
img.style.width = Math.round(imgWidth * scaleRatio) + 'px';
img.style.height = Math.round(imgHeight * scaleRatio) + 'px';
}
});
});
示例一
在一个500x500的容器内展示宽度为800px,高度为300px的图片。
HTML代码:
<div class="container">
<img src="example-1.jpg" alt="example image">
</div>
示例在线演示:点击查看
示例二
在一个500x500的容器内展示宽度为300px,高度为800的图片。
HTML代码:
<div class="container">
<img src="example-2.jpg" alt="example image">
</div>
示例在线演示:点击查看
沃梦达教程
本文标题为:纯js实现div内图片自适应大小(已测试,兼容火狐)


基础教程推荐
猜你喜欢
- Loaders.css免费开源加载动画框架介绍 2025-01-23
- Django操作cookie的实现 2024-04-15
- html5视频如何嵌入到网页(视频代码) 2025-01-22
- webpack学习笔记一:安装webpack、webpack-dev-server、内存加载js和html文件、loader处理非js文件 2023-10-29
- clientX,pageX,offsetX,x,layerX,screenX,offsetLeft区别分析 2024-01-08
- 创建Vue3.0需要安装哪些脚手架 2025-01-16
- JSONObject与JSONArray使用方法解析 2024-02-07
- js判断一个对象是否在一个对象数组中(场景分析) 2022-10-21
- 纯css实现漂亮又健壮的tooltip的方法 2024-01-23
- Bootstrap学习笔记之css组件(3) 2024-01-22