在我們 Shopify 網站的產品系列頁面中,由于產品標題的長度不同,每個產品卡片中的查看詳細資訊按鈕都未對齊。為了對齊它們,我們決定使用純 JavaScript 將一行中所有產品卡的產品標題的最小高度設定為同一行中三個中的最高值。下面是實作這一點的完整邏輯。
邏輯:
- 查找“.card__info”的所有選擇器
- 設定每行卡片的數量,根據 window.innerWidth 進行檢查
- 設定最大高度 = 0;
- Foreach card__info 選擇器,執行以下命令:
- 獲取卡片__title
- 獲取高度。
- 設定最大高度 = max (max_height, 新高度)
- Foreach card__info 選擇器,執行以下命令:
- 獲取卡片__title
- 將最小高度設定為最大值。
理想 - 逐行執行 window.innerWidth 768px 及以上 - 3 列其他 2 列
下面的代碼只是解決方案的第一部分。我在控制臺中得到的輸出是 Max Height: NaN 而不是實際高度,因為下面鏈接的集合頁面中有 15 種產品及其標題。
JavaScript 代碼:
// Find All selectors of ".card__info"
let allCardInfo = document.querySelectorAll(".card__info");
// Set number of cards per row, to check based on window.innerWidth
var numCardsPerRow = ((window.innerWidth >= 768) ? 3 : 2);
var maxHeight = 0; // Set max height = 0;
// Foreach card__info selector, execute the following:
allCardInfo.forEach(element => {
let cardTitle = element.querySelector(".card__title"); // Get the card__title
let cardTitleHeight = cardTitle.height; // Get the height.
// Set max height = max (max_height, new height)
maxHeight = Math.max(maxHeight, cardTitleHeight);
console.log('Max Height: ' maxHeight);
});
uj5u.com熱心網友回復:
.height不是 JS 中 html 元素的屬性,因此您可以使用
getComputedStyle(element)[0].height取而代之的是,
getComputedStyle是一種很好的視窗物件方法,可以幫助您獲取元素的所有樣式(無論它們是行內的、內部的還是外部的)
我還測驗了@James 在評論中所說的
let cardTitleHeight = cardTitle.clientHeight;
它也有效...
你也可以element.getClientRects用來獲取元素的高度
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/470290.html
標籤:javascript html jQuery 前端 dhtml
下一篇:IP編址
