设图片宽高比例是1:1,
显示窗口是1:1就正常放,
显示窗口是2:2或0.5:0.5就等比放大或缩小,
显示窗口是2:1 就以高为100%,宽显示中间部分,左右屏幕外有图片原始宽度的25%
显示窗口是1:2 就以宽为100%,高显示中间部分,上下屏幕外有图片原始宽度的25%
使用jquery 实现了,但是JS是等图片加载完以后再处理的,请问一下使用CSS是否可以实现?
const ImageController = (function() {
// 私有变量
let settings = {
debug: false
};
/**
* 初始化模块
* @param {Object} options - 配置选项
* @returns {Object} - 返回模块实例
*/
function init(options) {
if (options) {
settings = $.extend(settings, options);
}
return this;
}
/**
* 计算图片尺寸和位置
* @param {Number} targetWidth - 目标容器宽度
* @param {Number} targetHeight - 目标容器高度
* @param {Number} imgWidth - 图片原始宽度
* @param {Number} imgHeight - 图片原始高度
* @returns {Object} - 计算后的尺寸和位置
*/
function calculateDimensions(targetWidth, targetHeight, imgWidth, imgHeight) {
let newWidth, newHeight, left = 0, top = 0;
// 计算宽高比
const targetRatio = targetWidth / targetHeight;
const imgRatio = imgWidth / imgHeight;
if (imgRatio > targetRatio) {
// 图片更宽,以高度为基准
newHeight = targetHeight;
newWidth = imgWidth * (targetHeight / imgHeight);
left = (targetWidth - newWidth) / 2;
} else {
// 图片更高,以宽度为基准
newWidth = targetWidth;
newHeight = imgHeight * (targetWidth / imgWidth);
top = (targetHeight - newHeight) / 2;
}
return {
width: newWidth,
height: newHeight,
left: left,
top: top
};
}
/**
* 缩放并居中图片
* @param {Number} containerWidth - 容器宽度
* @param {Number} containerHeight - 容器高度
* @param {String|jQuery} selector - 图片容器选择器或jQuery对象
*/
function zoomPic(containerWidth, containerHeight, selector) {
// 确保参数有效
if (!containerWidth || !containerHeight || !selector) {
if (settings.debug) {
console.error('参数无效', containerWidth, containerHeight, selector);
}
return;
}
// 处理可能的jQuery对象
const $containers = typeof selector === 'string' ? $(selector) : selector;
// 遍历每个容器
$containers.each(function() {
const $container = $(this);
const $img = $container.find('img');
// 确保图片存在
if (!$img.length) {
if (settings.debug) {
console.warn('容器内未找到图片元素', this);
}
return;
}
// 获取图片自然尺寸
const imgWidth = $img[0].naturalWidth || $img.width();
const imgHeight = $img[0].naturalHeight || $img.height();
// 计算新尺寸和位置
const dimensions = calculateDimensions(
containerWidth,
containerHeight,
imgWidth,
imgHeight
);
// 应用样式
$img.css({
width: dimensions.width > 0 ? dimensions.width : '',
height: dimensions.height > 0 ? dimensions.height : '',
left: dimensions.left,
top: dimensions.top,
position: 'absolute'
});
if (settings.debug) {
console.log('应用图片样式', dimensions);
}
});
}
// 公开API
return {
init: init,
zoomPic: zoomPic,
calculateDimensions: calculateDimensions // 导出以便单元测试
};
})();
// 使用示例
$(document).ready(function() {
// 初始化图片控制器
ImageController.init({
debug: false
});
// 假设页面上有图片容器
// ImageController.zoomPic(400, 300, '.image-container');
// 也可以在窗口大小变化时重新调整
$(window).on('resize', function() {
// 假设页面上有图片容器
// ImageController.zoomPic(400, 300, '.image-container');
});
});
CSS
background-size
:cover
参考 MDN 文档
https://developer.mozilla.org/zh-CN/docs/Web/CSS/background-size