全局标记变量
let displaySize = 3; //默认展示图片数量let displayIndex = 0; //默认从第一张开始显示
resize 事件
$(window).on('resize', function () { let width = $(this).width(); let $li = $('.similar .similar-home'); let len = $li.length; if (width > 1020) { displaySize = 3; $li.hasClass('middle-screen') && $li.removeClass('middle-screen'); $li.hasClass('small-screen') && $li.removeClass('small-screen'); } else if (width > 600) { displaySize = 2; $li.hasClass('middle-screen') || $li.addClass('middle-screen'); $li.hasClass('small-screen') && $li.removeClass('small-screen'); } else { displaySize = 1; $li.hasClass('middle-screen') && $li.removeClass('middle-screen'); $li.hasClass('small-screen') || $li.addClass('small-screen'); } let wholeList = Array.prototype.slice.call($('.similar .similar-home')); toggleShowList(wholeList, displayIndex, displaySize); }).trigger('resize');
封装的函数
/** * * @param {*} wholeList arrayLiked object dom-list * @param {*} displayIndex int * @param {*} displaySize int */function toggleShowList(wholeList, displayIndex, displaySize) { let len = wholeList.length; let showList = []; if (displayIndex + displaySize < len) { showList = wholeList.splice(displayIndex, displaySize); }else{ showList = wholeList.splice(displayIndex, len).concat(wholeList.splice(0,(displayIndex+displaySize-len))); } for (let i = 0, len = wholeList.length; i < len; i++) { $(wholeList[i]).css('display', 'none'); } for (let i = 0, len = showList.length; i < len; i++) { $(showList[i]).css('display', 'block'); }}
点击切换
// Data.CLick 的值为navigator.userAgent.match(/iphone|ipad|ipod|android|windows phone/i)?'touchstart':'click';$('.similar').on(Data.CLICK, '.change-house', function () { let wholeList = Array.prototype.slice.call($('.similar .similar-home')); let maxIndex = wholeList.length; displayIndex += displaySize; if (displayIndex > maxIndex) { displayIndex = 0; } toggleShowList(wholeList, displayIndex, displaySize);});