如何在Vue 2中用JavaScript实现CSS的:nth-child功能?
用JavaScript实现CSS :nth-child(7n+k)的宽高比分配逻辑
核心逻辑很简单:CSS的:nth-child是从1开始计数,而数组的index是从0开始的,所以先把index转成1-based的项数,再用取模运算实现每7项一组的循环判断。
实现代码(Vue2 computed)
computed: { parsedItems() { // 按顺序定义:nth-child(7n+1)到(7n+7)对应的宽高比 const aspectRatios = [1.5, 2, 0.8, 1, 2.2, 1.2, 0.9]; return this.items?.map((obj, index) => { // 转成1-based的项数,和:nth-child的计数规则对齐 const itemNumber = index + 1; // 计算当前项在7项组里的位置(1-7):取模为0时对应第7项 const groupPosition = itemNumber % 7 === 0 ? 7 : itemNumber % 7; // 取对应位置的宽高比(数组是0-based,所以减1) const aspectRatio = aspectRatios[groupPosition - 1]; return { ...obj, aspectRatio }; }) || []; } }
逻辑说明
- 第1项(
index=0)→itemNumber=1→groupPosition=1→ 对应:nth-child(7n+1)的宽高比 - 第7项(
index=6)→itemNumber=7→ 取模为0,所以groupPosition=7→ 对应:nth-child(7n+7)的宽高比 - 第8项(
index=7)→itemNumber=8→8%7=1→ 回到:nth-child(7n+1)的规则,完美循环
灵活扩展:单独定义每个位置的规则
如果每个:nth-child的宽高比逻辑不一样,也可以用switch单独处理:
computed: { parsedItems() { return this.items?.map((obj, index) => { const itemNumber = index + 1; const groupPosition = itemNumber % 7 === 0 ? 7 : itemNumber % 7; let aspectRatio; switch(groupPosition) { case 1: // :nth-child(7n+1) aspectRatio = 1.5; break; case 2: // :nth-child(7n+2) aspectRatio = 2; break; case 3: // :nth-child(7n+3) aspectRatio = 0.8; break; case 4: // :nth-child(7n+4) aspectRatio = 1; break; case 5: // :nth-child(7n+5) aspectRatio = 2.2; break; case 6: // :nth-child(7n+6) aspectRatio = 1.2; break; case 7: // :nth-child(7n+7) aspectRatio = 0.9; break; default: aspectRatio = 1; // 默认宽高比 } return { ...obj, aspectRatio }; }) || []; } }
内容的提问来源于stack exchange,提问作者Svebor Sorić
相关产品推荐
相关产品推荐

