由于IE系列不接受CSS3列属性,我正在尝试使用javascript / jquery将li
列表拆分为5列。在这个过程中,我被告知向后循环数组比正常循环更快。我试过了,但它给了我一个有趣的结果。最后一列显示为第1列,我不想要。我不知道代码有什么问题。最重要的是,代码在浏览器中读取速度很慢......请给我一些启示。
JS / jQuery的:
var JL = {}, JL.Module = {};
JL.Module.indexSort = function(){
var indexContainers = $('.index-section'),
indexControls = $('ul.index-navigation li'),
ieIndexContainers = $('.ie6, .ie7, .ie8, .ie9').find('.index-section'),
ulWrap = '<ul class="new-col" />',
colCount = 5,
subLi;
indexContainers.hide().filter(':first').show();
indexControls.filter(':first').addClass('selected');
//IE family don't accept css columns properties, so have to use JS
ieIndexContainers.each(function () {
var thisElem = $(this),
indexUl = thisElem.find('ul'),
indexLi = thisElem.find('li'),
indexLiLen = indexLi.length,
liPerCol = Math.ceil(indexLiLen / colCount),
lastColCount = indexLiLen % liPerCol,
sliceStart = indexLiLen - lastColCount,
sliceEnd = indexLiLen,
subLi,
i;
ieIndexContainers.find('ul').addClass('new-col');
setTimeout(function(){
sliceEnd = 0;
sliceStart = -1;
// Looping the array backwards
for(i = colCount - 1; i > 0; i--){
sliceEnd = sliceStart;
sliceStart = (sliceEnd - liPerCol >= 0) ? sliceEnd - liPerCol : 0;
subLi = indexLi.slice(sliceStart, sliceEnd);
indexUl.after($(ulWrap).append(subLi));
}
ieIndexContainers.find('.new-col').show();
}, 0);
});
}
HTML:
<div id="s" class="index-section">
<h2>s</h2>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Aorem</a></li>
<li><a href="#">Apsum</a></li>
<li><a href="#">Aonor</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asdijnd oasd</a></li>
<li><a href="#">Awrom</a></li>
<li><a href="#">Aoidn iojd</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asddewdwe</a></li>
<li><a href="#">Apsum</a></li>
<li><a href="#">Aonor</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asdijnd oasd</a></li>
<li><a href="#">Awrom</a></li>
<li><a href="#">Aoidn iojd</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asddewdwe</a></li>
</ul>
</div>
答案 0 :(得分:2)
只需将其向前循环即可。速度较慢与不缓存数组的长度有关。但是,您会在colCount
中缓存for循环的上限。不要担心性能,只需以正确的方式循环。让它向前推进。
答案 1 :(得分:0)
至少,您需要更新for循环:
// Looping the array backwards
for(i = colCount - 1; i > 0; i--){
sliceEnd = sliceStart;
sliceStart = (sliceEnd - liPerCol >= 0) ? sliceEnd - liPerCol : 0;
subLi = indexLi.slice(sliceStart, sliceEnd);
indexUl.after($(ulWrap).append(subLi));
}
应该是:
// Looping the array backwards
for(i = colCount - 1; i >= 0; i--){
sliceEnd = sliceStart;
sliceStart = (sliceEnd - liPerCol >= 0) ? sliceEnd - liPerCol : 0;
subLi = indexLi.slice(sliceStart, sliceEnd);
indexUl.after($(ulWrap).append(subLi));
}
答案 2 :(得分:0)
你应该执行切片,然后调整新的sliceEnd和sliceStart:
for (i = colCount - 1; i > 0; i--) {
subLi = indexLi.slice(sliceStart, sliceEnd);
indexUl.after($(ulWrap).append(subLi));
sliceEnd = sliceStart;
sliceStart = (sliceEnd - liPerCol >= 0) ? sliceEnd - liPerCol : 0;
}
这将解决您的列排序问题。没有关于数组循环前进/后退的评论。