阻止img溢出可以通过以下几种方式实现:
.container {
width: 200px;
height: 200px;
overflow: hidden;
}
.container img {
width: 100%;
height: auto;
}
window.addEventListener('resize', function() {
var container = document.querySelector('.container');
var img = container.querySelector('img');
var containerWidth = container.offsetWidth;
var containerHeight = container.offsetHeight;
var imgWidth = img.naturalWidth;
var imgHeight = img.naturalHeight;
var containerRatio = containerWidth / containerHeight;
var imgRatio = imgWidth / imgHeight;
if (containerRatio > imgRatio) {
img.style.width = '100%';
img.style.height = 'auto';
} else {
img.style.width = 'auto';
img.style.height = '100%';
}
});
领取专属 10元无门槛券
手把手带您无忧上云