[英]set div height to an image height with javascript
I have an image gallery with a main image and some thumbnail images on the right side of the main image.我有一个图片库,其中包含主图片和主图片右侧的一些缩略图。 I want to set the height of the thumbnails div the same as the main image.我想将缩略图 div 的高度设置为与主图像相同。 The problem is, this image is always different so it doesn't have a static height.问题是,这张图片总是不同的,所以它没有 static 的高度。 Tried to use javascript to get it's height then give it to the thumbnails div, but it doesn't do anything.尝试使用 javascript 来获取它的高度,然后将其提供给缩略图 div,但它什么也没做。
<div class="gallery">
<a href="images/1.jpg">
<div class="main-image">
<img class="card-img-top" id="modal-img-top" src="images/1.jpg" alt="Fő kép">
</div>
<div class="image-container" id="image-thumbnails">
<img src="images/1.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor2.jpg" alt="Egy kép a hirdetésről">
<img src="images/2.jpg" alt="Egy kép a hirdetésről">
<img src="images/1.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor2.jpg" alt="Egy kép a hirdetésről">
<img src="images/2.jpg" alt="Egy kép a hirdetésről">
</div>
</a>
<a href="images/motor.jpg"></a>
<a href="images/motor2.jpg"></a>
<a href="images/2.jpg"></a>
<a href="images/1.jpg"></a>
</div>
<script type="text/javascript">
const img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
document.getElementById("image-thumbnails").style.height = this.height;
}
img.src = document.getElementById("modal-img-top").getElementsByTagName('img');
</script>
Edit: Ok let's have another try.编辑:好的,让我们再试一次。
The main issue is to size your main image which should stay in its ratio and be wrapped in its parent.主要问题是调整主图像的大小,主图像应保持其比例并包裹在其父图像中。 After trial and error there seems to be no easy method to archive this.经过反复试验,似乎没有简单的方法来存档它。 I also tried object-fit
property, but event this is not working as you want to.我还尝试object-fit
属性,但事件并不像你想要的那样工作。 So here are my two solutions.所以这是我的两个解决方案。
Solution 1: The most easy way is to use a div
with the background-image
property instead of an img
.解决方案 1:最简单的方法是使用具有background-image
属性的div
而不是img
。 As you see in the solution below, the main-image
is a div
now.正如您在下面的解决方案中看到的, main-image
现在是一个div
。 You could also use the element .image-wrapper
as the background image.您还可以使用元素.image-wrapper
作为背景图像。 But I wrapped a main-image
into it to get some padding between these two elements.但是我将main-image
包装到其中,以便在这两个元素之间进行一些填充。
Solution 2: Instead of using the background-image
property you can still use a img
, but you'll need some javascript and calculations.解决方案 2:您仍然可以使用img
而不是使用background-image
属性,但是您需要一些 javascript 和计算。 The calculation is done by the function calculateMainImage
.计算由 function calculateMainImage
完成。 It is not too complex, but it needs some lines.它不太复杂,但需要一些线条。 The strategy is this:策略是这样的:
width: 100%
).假设图像适合其父级(在 css: width: 100%
中)。 So calculate the image dimensions for this assumption.因此,计算此假设的图像尺寸。 This function is also called when the document is ready (initialization) and when the window resizes ( window.onresize
).当文档准备好(初始化)和 window 调整大小时( window.onresize
)也会调用此 function 。
let mainImage = document.querySelector('.main-image'); let thumbnails = document.querySelectorAll('.thumbnail'); thumbnails.forEach(thumbnail => { thumbnail.addEventListener('click', () => { let backgroundImage = 'url(' + thumbnail.src +')'; mainImage.style.backgroundImage = backgroundImage; }); });
.gallery{ position: relative; width: 100%; height: 400px; background: #dedede; display: grid; grid-template-columns: 70% 30%; }.image-wrapper{ position: relative; width: 100%; height: 100%; background: #aaa; padding: 12px; box-sizing: border-box; }.main-image{ position: relative; width: 100%; height: 100%; background-image: url("https://via.placeholder.com/350x150"); background-size: contain; background-repeat: no-repeat; background-position: center; }.thumbnail-wrapper{ position: relative; width: 100%; height: 100%; overflow-y: auto; padding: 12px; box-sizing: border-box; }.thumbnail-wrapper >.thumbnail:not(:last-child){ margin-bottom: 12px; }.thumbnail{ position: relative; display: block; width: 100%; height: auto; margin-left: auto; margin-right: auto; cursor: pointer; }
<section class="gallery"> <:-- Main image --> <div class="image-wrapper"> <div class="main-image"> </div> </div> <.-- Thumbnails --> <div class="thumbnail-wrapper"> <img class="thumbnail" src="https.//via:placeholder.com/350x150"> <img class="thumbnail" src="https.//via:placeholder.com/200x100"> <img class="thumbnail" src="https.//via:placeholder.com/140x100"> <img class="thumbnail" src="https.//via:placeholder.com/350x65"> <img class="thumbnail" src="https.//via:placeholder.com/350x150"> <img class="thumbnail" src="https.//via:placeholder.com/200x100"> <img class="thumbnail" src="https.//via.placeholder.com/140x100"> </div> </section>
let gallery = document.querySelector('.gallery'); let container = document.querySelector('.container'); let mainImage = document.querySelector('.main-image'); let thumbnails = document.querySelectorAll('.thumbnail'); (function(){ // Document ready calculateMainImage(); // When window resizes window.addEventListener('resize', () => { calculateMainImage(); }); })(); thumbnails.forEach(thumbnail => { thumbnail.addEventListener('click', () => { mainImage.src = thumbnail.src; // Fit image to container calculateMainImage(); }); }); function calculateMainImage(){ // Reset current dimensions mainImage.style.width = 'initial'; mainImage.style.height = 'initial'; // Container dimensions let containerWidth = container.getBoundingClientRect().width; let containerHeight = container.getBoundingClientRect().height; // Image dimensions let width = mainImage.getBoundingClientRect().width; let height = mainImage.getBoundingClientRect().height; let ratio = width / height; // Calculate image dimensions when width: 100% let maxWidth = containerWidth; let maxHeight = maxWidth / ratio; // Check if image fits in parent if(maxHeight > containerHeight){ // Scale image down. Recalculate image's width let newHeight = containerHeight; let newWidth = newHeight * ratio; setMainImageSize(newWidth, newHeight); }else{ setMainImageSize(maxWidth, maxHeight); } } function setMainImageSize(width, height){ mainImage.style.width = width + 'px'; mainImage.style.height = height + 'px'; }
.gallery{ position: relative; width: 100%; height: 400px; background: #dedede; display: grid; grid-template-columns: 70% 30%; }.image-wrapper{ position: relative; width: 100%; height: 100%; background: #aaa; padding: 12px; box-sizing: border-box; }.container{ position: relative; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }.main-image{ position: relative; flex-grow: 0; flex-shrink: 0; }.thumbnail-wrapper{ position: relative; width: 100%; height: 100%; overflow-y: auto; padding: 12px; box-sizing: border-box; }.thumbnail-wrapper >.thumbnail:not(:last-child){ margin-bottom: 12px; }.thumbnail{ position: relative; display: block; width: 100%; height: auto; margin-left: auto; margin-right: auto; cursor: pointer; }
<section class="gallery"> <:-- Main image --> <div class="image-wrapper"> <div class="container"> <img class="main-image" src="https.//via.placeholder:com/200x100"> </div> </div> <.-- Thumbnails --> <div class="thumbnail-wrapper"> <img class="thumbnail" src="https.//via:placeholder.com/350x150"> <img class="thumbnail" src="https.//via:placeholder.com/200x100"> <img class="thumbnail" src="https.//via:placeholder.com/140x100"> <img class="thumbnail" src="https.//via:placeholder.com/350x65"> <img class="thumbnail" src="https.//via.placeholder.com/350x150"> </div> </section>
When you have several gallerys on your page and use use solution #1, then you need to add this JS snipped.当您的页面上有多个画廊并使用解决方案 #1 时,您需要添加此 JS 片段。
let gallerys = document.querySelectorAll('.gallery');
gallerys.forEach(gallery => {
updateGalleryPictures(gallery)
});
function updateGalleryPictures(gallery) {
// Get gallery's main image
let mainImage = gallery.querySelector('.main-image');
if (mainImage === null) return;
// Get gallery's thumbnail images
let thumbnails = gallery.querySelectorAll('.thumbnail');
// Change the background-image property on click
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
let backgroundImage = 'url(' + thumbnail.src + ')';
mainImage.style.backgroundImage = backgroundImage;
});
});
// Initialize background-image property using the 1st thumbnail image
let firstThumbnail = thumbnails[0];
if (firstThumbnail === null || firstThumbnail === undefined) return;
let initialBackgroundImage = 'url(' + firstThumbnail.src + ')';
mainImage.style.backgroundImage = initialBackgroundImage;
}
Step 1: Add the property overflow: hidden;
第一步:添加属性overflow: hidden;
to the class .image-wrapper
and create a new class到 class .image-wrapper
并创建一个新的 class
.baguettebox-image{
opacity: 0 !important;
}
Step 2: Change the structure of the main-image
setup.第 2 步:更改main-image
设置的结构。
<div class="image-wrapper">
<div class="main-image"> <!-- THis is the baguette box -->
<a class="baguettebox-link" href="">
<img class="baguettebox-image" src=""></a>
</a>
</div>
</div>
Step 3: Change the JS snipped of the 1st update to: Note that the baguette boxes are also initialized in this script.第 3 步:将第 1 次更新的 JS 片段更改为: 请注意,长方形面包盒也在该脚本中进行了初始化。 According to the documentation querySelectorAll
is used, so all boxes ( .main-image
) should be initialized.根据使用的文档querySelectorAll
,因此应初始化所有框( .main-image
)。
let gallerys = document.querySelectorAll('.gallery');
gallerys.forEach(gallery => {
updateGalleryPictures(gallery);
});
// Initialize all baguette boxes
baguetteBox.run('.main-image');
function updateGalleryPictures(gallery) {
// Get gallery's thumbnail images
let thumbnails = gallery.querySelectorAll('.thumbnail');
// Change the background-image property on click
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
updateMainImage(gallery, thumbnail.src)
});
});
// Initialize background-image property using the 1st thumbnail image
let firstThumbnail = thumbnails[0];
if (firstThumbnail === null || firstThumbnail === undefined) return;
updateMainImage(gallery, firstThumbnail.src)
// Initialize baguette
}
function updateMainImage(gallery, src) {
// Get main image and check if it exists
let mainImage = gallery.querySelector('.main-image');
if (mainImage === null) return;
mainImage.style.backgroundImage = 'url(' + src + ')';
// Get baguette elements
let boxLink = gallery.querySelector('.baguettebox-link');
let boxImage = gallery.querySelector('.baguettebox-image');
// Update baguette elements href and src
if (boxLink !== null && boxLink !== undefined) boxLink.href = src;
if (boxImage !== null && boxImage !== undefined) boxImage.src = src;
}
document.getElementById("image-thumbnails").style.height = '300px';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.