在我们Shopify网站的集合页面中,由于产品标题的长度不同,每个产品卡中的VIEW DETAILS按钮都不对齐。为了对齐它们,我们决定使用纯JavaScript将一行中所有产品卡的产品标题的最小高度设置为同一行中三个产品卡中最高的。下面是实现此功能的完整逻辑。
逻辑:
- 查找".card__info">
- 设置每行卡片数量,根据window.innerWidth 进行检查
- Set max height = 0;
- Foreach card__info选择器,执行以下操作:
- 获取card_title
- 获取高度
- 设置最大高度= max (max_height, new height)
- Foreach card__info选择器,执行以下操作:
- 获取card_title
- 设置最小高度为最大值
理想-按行排列window.innerWidth768px及以上- 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);
});
.height
在JS中不是html元素的属性,所以你可以使用
getComputedStyle(element)[0].height
代替,
getComputedStyle
是一个很好的窗口对象的方法,可以帮助您获得一个元素的所有样式(无论他们是内联,内部或外部)
我还测试了@James关于
的评论let cardTitleHeight = cardTitle.clientHeight;
it works too…
你也可以使用element.getClientRects
来获取元素的高度