如何用jQuery排序div,实现col-sm-6与col-sm-12交替布局?
实现col-sm-6与col-sm-12的交替布局排序
你的需求是把col-sm-6和col-sm-12的div排成「两个6列 + 一个12列」的循环交替布局,单纯用jQuery的sort函数没法直接实现这种分组逻辑——因为sort是基于元素两两比较的排序规则,无法跟踪分组状态。更合适的做法是先分离两种元素,再手动构建目标序列:
实现步骤
- 分别筛选出未隐藏的
col-sm-6和col-sm-12元素 - 按「两个6列元素 + 一个12列元素」的循环规则拼接新序列
- 将新序列重新追加到
.row容器中
完整代码
// 分离两种列元素(排除.d-none隐藏项) const col6List = $('.col:not(.d-none)[data-width="6"]').toArray(); const col12List = $('.col:not(.d-none)[data-width="12"]').toArray(); const sortedColumns = []; let col6Index = 0; let col12Index = 0; // 按6+6+12的模式构建排序后的序列 while (col6Index < col6List.length || col12Index < col12List.length) { // 先添加最多两个col-sm-6 if (col6Index < col6List.length) { sortedColumns.push(col6List[col6Index]); col6Index++; } if (col6Index < col6List.length) { sortedColumns.push(col6List[col6Index]); col6Index++; } // 再添加一个col-sm-12(如果还有剩余) if (col12Index < col12List.length) { sortedColumns.push(col12List[col12Index]); col12Index++; } } // 更新row容器内的元素 $('.row').empty().append(sortedColumns);
补充说明
如果坚持要用sort函数,几乎无法实现这种分组交替的布局——因为sort的比较函数只能返回-1、0、1来决定两个元素的先后,无法记录当前是第几个元素、属于哪一组,所以不建议用sort来完成这个需求。
内容的提问来源于stack exchange,提问作者mawo
相关产品推荐
相关产品推荐

