我目前有一个图库,其中左侧有全尺寸的图像,而左侧的所有其他图像都像这样:
<div class='col-md-7'>
<img src='something'>
</div>
<div class='col-md-5'>
<ul>
<li ng-repeat for all the images in the array>
<img thumbnail for the image, on click it changes the source of the main image>
</li>
</ul>
</div>
问题是,图像可以具有不同的高度,并且随着img高度的变化,主容器和每个缩略图的高度也会变化(因为它们对父级大小有响应)。有没有一种方法可以确定画廊的初始高度,并在用户更改图像时保持这种初始高度?我不想设置静态数值,因为它应该随屏幕尺寸缩放,并且由于同一页面中可以有多个图库,所以我需要每个图库都记住自己的高度。
在示例中可以看到,我正在使用bootstrap和angularJS以及jQuery,因此可以使用这些框架可用的工具。
答案 0 :(得分:0)
获取所有您不想改变高度的offsetHeight
元素的初始img
并将其height
设置为您获得的值。
在下面的代码段中,该行是:
img.style.height = img.offsetHeight + "px";
let gallery = [
'https://picsum.photos/200/100/?image=1080',
'https://picsum.photos/200/200/?image=1063',
'https://picsum.photos/500/200/?image=1060',
'https://picsum.photos/300/300/?image=1059',
'https://picsum.photos/200/300/?image=1070',
'https://picsum.photos/300/200/?image=1071'
];
let thumbs = document.getElementById("thumbnails");
for (let i = 1; i < gallery.length; i++) {
thumbs.appendChild(thumbs.firstElementChild.cloneNode(true));
}
let img = document.querySelector(".col-md-7").firstElementChild;
gallery.forEach((url, i) => {
thumbs.children[i].firstChild.src = url;
});
thumbs.addEventListener("click", event => {
if (event.target.tagName === "IMG") {
img.src = event.target.src;
}
});
img.src = gallery[0];
img.style.height = img.offsetHeight + "px";
// The above last line is the code keeping the initial height.
#thumbnails {
list-style-type: none;
padding: 0;
}
#thumbnails li {
float: left;
height: 35px;
width: 50px;
margin: 10px;
background: #fde;
}
#thumbnails img {
width: 100%;
height: 100%;
}
<div class='col-md-7'>
<img>
</div>
<div class='col-md-5'>
<ul id="thumbnails">
<li><img></li>
</ul>
</div>
编辑:(回答评论)
据我到目前为止的了解,您可以执行以下操作:
HTML
每个画廊都被包裹在<div class="gallery"></div>
中。缩略图源由ng-repeat
<div class="gallery">
<div class='col-md-7'>
<img src='something'>
</div>
<div class='col-md-5'>
<ul class="thumbnails">
<li ng-repeat="some-token">
<img src="{{img.src}}">
<!-- img.src here represents the url from each
iteration in your data -->
</li>
</ul>
</div>
</div>
<div class="gallery">
<div class='col-md-7'>
<img src='something'>
</div>
<div class='col-md-5'>
<ul class="thumbnails">
<li ng-repeat="some-token">
<img src="{{img.src}}">
</li>
</ul>
</div>
</div>
JS
代码在galleries
集合中的每个画廊上运行,因此每个画廊都有自己的范围。
let galleries = document.getElementsByClassName("gallery");
[].forEach.call(galleries, gallery => {
let image = gallery.querySelector("img");
image.style.height = image.offsetHeight + "px"; // Initial height
let thumbs = gallery.querySelector(".thumbnails");
thumbs.addEventListener("click", event => {
if (event.target.tagName === "IMG") {
image.src = event.target.src;
}
});
});