Created
September 9, 2016 05:32
-
-
Save VitalyKondratiev/fb5df3133f18d5ba456e9c736c376439 to your computer and use it in GitHub Desktop.
Выравнивание изображений в один ряд (чистый JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function images_in_row(selector) { | |
var galleries = document.querySelectorAll(selector); | |
var galleryMarginWidth = 5; | |
Array.prototype.forEach.call(galleries, function(gallery, index) { | |
var images = gallery.getElementsByTagName("img"); | |
if (images.length == 0) { | |
return; | |
} | |
var galleryWidth = parseFloat(getComputedStyle(gallery).width).toFixed(2); | |
var galleryUsableWidth = galleryWidth - (galleryMarginWidth * images.length * 2); | |
var minHeight = images[0].naturalHeight; | |
var imagesSizes = []; | |
Array.prototype.forEach.call(images, function(image, index) { | |
imagesSizes.push({ | |
"width": image.naturalWidth, | |
"height": image.naturalHeight, | |
"wh": image.naturalWidth / image.naturalHeight, | |
"hw": image.naturalHeight / image.naturalWidth | |
}); | |
if (minHeight > image.naturalHeight) { | |
minHeight = image.naturalHeight; | |
} | |
}); | |
Array.prototype.forEach.call(images, function(image, index) { | |
if (minHeight < image.naturalHeight) { | |
ratio = minHeight / imagesSizes[index].height; | |
newImageSize = { | |
"width": imagesSizes[index].width * ratio, | |
"height": minHeight, | |
"wh": imagesSizes[index].wh, | |
"hw": imagesSizes[index].hw | |
}; | |
imagesSizes[index] = newImageSize; | |
} | |
}); | |
var summaryWidth = 0; | |
imagesSizes.forEach(function(element, index) { | |
summaryWidth += imagesSizes[index].width; | |
}); | |
var widthMultiplier = summaryWidth / galleryUsableWidth; | |
Array.prototype.forEach.call(images, function(image, index) { | |
ratio = minHeight / imagesSizes[index].height; | |
newImageSize = { | |
"width": imagesSizes[index].width / widthMultiplier, | |
"height": imagesSizes[index].height / widthMultiplier, | |
"wh": imagesSizes[index].wh, | |
"hw": imagesSizes[index].hw | |
}; | |
imagesSizes[index] = newImageSize; | |
image.style.width = imagesSizes[index].width + 'px'; | |
console.log(newImageSize); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment