簡體   English   中英

根據列表中最大的高度/寬度調整所有項目的大小

[英]Resize all items based on biggest height/width in a list

我有這個清單

<ul>
    <li><img src="https://via.placeholder.com/650x100"></li>
    <li><img src="https://via.placeholder.com/150x350"></li>
    <li><img src="https://via.placeholder.com/100"></li>
    <li><img src="https://via.placeholder.com/350x350"></li>
</ul>

每個li的寬度和高度都不同。 我需要渲染如下:

1) Each li needs to have the width of the widest li
2) Each li needs to have the height of the tallest li 
3) There is a max-width and max-height for li

因此,使用Flexbox我可以輕松滿足1) 演示,但是我不能滿足CSS的寬度和高度。 什么是這里的首選解決方案。 沒有javascript甚至可能嗎?

更新:我已經在這里實施了建議

我首選的解決方案是使用Javscript,我不知道您如何單獨使用CSS。 像這樣的事情,您應該確保已加載圖像。

 const forEach = Function.bind.call(Function.call, Array.prototype.forEach); const reduce = Function.bind.call(Function.call, Array.prototype.reduce); const sizeProperties = ['height', 'width']; const images = document.querySelectorAll('ul>li>img'); const size = reduce(images, (dimensions, image) => { const dimension = window.getComputedStyle(image); sizeProperties.forEach((property) => { dimensions[property] = Math.max( dimensions[property], Number.parseInt(dimension[property], 10), ); }); return dimensions; }, { width: 0, height: 0, }); forEach(images, (image) => { sizeProperties.forEach((property) => { image.parentNode.style[property] = `${size[property]}px`; }); }) 
 li { border-style: solid; border-width: 1px; list-style: none; } 
 <ul> <li><img src="https://via.placeholder.com/650x100"></li> <li><img src="https://via.placeholder.com/150x350"></li> <li><img src="https://via.placeholder.com/100"></li> <li><img src="https://via.placeholder.com/350x350"></li> </ul> 

即使使用像SASS這樣的預處理器,也無法檢索未知高度並將其存儲為CSS變量,因此無法單獨對CSS進行#2處理。 我意識到您只是希望使用樣式表,但是我提供了一個干凈的示例,說明如何結合CSSjQuery來實現#1和#2。

我希望這有幫助!

 var tallest; $('li').each(function() { tallest = tallest > $(this).height() ? tallest : $(this).height(); }); $('li').each(function() { $(this).height(tallest); }); 
 li { border: 1px solid gray; width: 100%; list-style-type: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><img src="https://via.placeholder.com/650x100"></li> <li><img src="https://via.placeholder.com/150x350"></li> <li><img src="https://via.placeholder.com/100"></li> <li><img src="https://via.placeholder.com/350x350"></li> </ul> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM