我想我找到了一个解决办法
here
. 我希望不要错过任何东西。
const ul = document.getElementsByClassName('list')[0];
const list = document.querySelectorAll('.list li');
const total = 5;
const offset = total / 2;
const circleTotalHeight = 30;
const totalViewable = 5;
const totalHeight = circleTotalHeight * list.length;
const totalViewableHeight = totalViewable * circleTotalHeight;
const limitTopOffset = totalViewableHeight - totalHeight; // -120
const halfViewableCount = totalViewable / 2; //2.5
const halfTotalCount = Math.ceil(list.length / 2); //4
const diffTotalAndView = list.length - totalViewable; // 3
let activeIndex = 0;
let nthActiveIndex = activeIndex + 1;
Array.prototype.forEach.call(list, (li) => {
li.addEventListener('click', (e) => {
let data = e.target.getAttribute("data-number");
const prevElement = `[data-number="${activeIndex}"]`;
const nextElement = `[data-number="${data}"]`;
ul.querySelector(nextElement).style.color = '#FFF';
ul.querySelector(prevElement).style.color = '#000';
nthActiveIndex = parseInt(data) + 1;
var nthActiveOffset = nthActiveIndex - halfViewableCount;
var nthOffset = Math.floor(nthActiveIndex - halfViewableCount);
if (nthOffset >= 0) {
//console.log(nthOffset);
if (nthOffset < diffTotalAndView) {
var topDistance = -1 * (nthOffset * circleTotalHeight);
ul.style.top = `${topDistance}px`;
} else {
ul.style.top = `${limitTopOffset}px`;
}
} else {
ul.style.top = '0';
}
activeIndex = data;
});
})